THE -MACINTOSH PERFORMANCE LIBRARY COMPUTER) .THE COMPLETE HYPERCARD HANDBOOK DANNY GOODMAN 2ND EDITION ForewordbyJtihnScutleyandaconversation with Bilt Atkinson. WITH 1.2 SUPPLEMENT A ''A masterpiece of a book'' steve bobker, m acL'ser The Complete HyperCard Handbook : Second Edition DANNY GOODMAN BANTAM BOOKS Toronto . New York ■ London . Sydney . Auckland ^5' For my father s r The Complete HyperCard Handbook. 2nd EdiHon A Bantam Book/ October 1988 •;». *^ -: Alt rights reserved Copyright © J 988 by Danny Goodrmn Cover design copyright © fay Bantam Boofcs, Inc. Interior design by Nancy Sugihara Production by Inter Text Productions, Inc. TT^roughout the booJc. tmde names and ^rodemarlcs ojsa^ ISBN 0-553-34577-X Published simultaneously in the United States and Canada Banum Books ar^ published by B^lam Bcota.^ fnc Its trademark, consisting of the words ■Baritam Books" and the potrayal of ^ "2^*"^= reirlster=d tn U .S. Patent and Tradeittark Office and oth« countries Marca Reglstrada, Bantar. Boots, inc. 666 Fifth Avenue, New York. New York 101O3 PRINTED IN THE UNITED STATES OF AMERICA BH 0987654321 Contents so:.. AcfciroiDtedgrments xv Foreword by John Sculley xvil A Coni>ersation ujith Bili Atkinson How to Use This Book xxxlll Preface to the 2nd Edition xxxiv Introduction Coping with the Information Revolution 1 The Historical Chain of Information 1 • Information Today 4 • Information Threads and Links 5 • Program Information 7 • The Database Software Heritage 8 • Hyper- Card and the Databases 10 • The Center of Your Macintosh World II" Programming for Poets 12 • Three Points of View 13 PART ONE Browsing Through HyperCard i5 xxi , . Chapter 1 The Browsing Building Blocks 17 h . V ; I User Preferences 1 7 • The Basic Elements ciij 19 • Stacks 20 • Backgrounds 23 • ' ' Cards 24 • Fields 27 • Buttons 27 • The Home Stack 28 • Recent 32 • The Message Box 34 vi' Chapter 2 Finding and Entering Information 41 Finding Information in the Real World 41 • Retrieval Environments 42 • Using the Browse Tool 43 • Flipping Through Cards 45 • Where Do I Click 47 • Finding Text 47 • Entering Text Information 56 Chapter 3 HyperCard Linking and Printing 65 Cross-Reference Information 65 • Hyper- Card Printing 68 PART TWO ^ ..:A-^.r H HyperCard's Authoring Environment 83 Chapter 4 Introduction to Authoring 85 What Authoring Means to You 85 • Author- ing Scenarios 86 • Accessing HyperCard's Authoring Tools 89 • The HyperCard Screen ^ 92 • HyperCard Menu Types 93 Chapter 5 All About Stacks 97 Two Stack Types 97 • Making a New Stack 100 • Protecting a Stack 105 Chapter 6 All About Layers 109 Object Layers 109 • Background and Card : Layers 111 • What the Browser Sees 112 •» J .' • Layers and Heterogeneous Stacks 116 Chapter 7 All About Backgrounds 119 Backgrounds and the Browser 119 • Blank Backgrounds 120 • Background Info... 121 Iv Chapter 8 All About Cards 123 Card and Background Interaction 123 • Card Properties 125 • Selecting Cards 126 Chapter 9 All About Fields 129 ' .0 Fields vs. Graphic Text 129 • Accessing the kx>T ) Field Tool 130 • Field Layer Properties 131 • Field Visual Properties 138 • Font Prop- - erties 143 • HyperTalk Properties 148 • Creating New Text Fields 149 • Customlz- ; « ing Field Properties 151 • Cloning Fields on the Same Card 152 • Changing a Field's Domain 156 • Copying and Pasting Fields fjfiiO • Between Stacks 158 hf'.f' Chapter 10 All About Buttons 161 ^ . ' ' ; J) What Buttons Do 161 • Accessing the But- J-^s ton Tool 162 • Button Layer Properties 163 • Button Visual Properties 165 • H3rpeiTalk Button Properties 175 • Creating New Buttons 175 • Cloning Buttons on the Same Card 177 • Changing a Button's Do- qsid'-^ main 180 • Copying and Pasting Buttons Between Stacks 182 Chapter 11 Basic Unking 185 - The Essence of a HyperCard Link 185 • ' " Instant Link Scripts 188 • New Button " ' Strategies 191 T.>iq;.i£iO Chapter 12 Introduction to HyperCard's Painting Tools 193 The Role of HyperCard Art 193 • Macintosh Painting 194 • Graphics Overview 196 • Undo- The Savior 199 V Chapter 13 HyperCard Painting Palettes 201 . The SelecUon Tool 201 • The Lasso Tool * 205 • The Pencil Tool 207 • The Paint- brush Tool 209 • The Eraser Tool 212 • The Straight Line Tool 214 • The SpraypalntTool 219 • The Rectangle Tool 221 • The Rounded Rectangle Tool 224 • > The Paint Bucket Tool 224 • The Oval Tool ••^ t j 228 • The Curve Tool 230 • The Text Tool 232 • The Regular Polygon Tool 236 • The Irregular Polygon Tool 240 • The Patterns Palette 242 Chapter 14 The Paint Menu 245 Select 246 • Select All 246 • FUl 246 • Invert 246 • Hckup 249 • Darken and Lighten 250 • Trace Edges 251 • Rotate Left and Rotate Right 252 • Flip Vertical and Flip Horizontal 252 • Opaque and Transparent 253 • Keep 254 • Revert 256 Chapter 15 The Options Menu 259 ^ Grid 259 • FatBits 262 • Power Keys 266 • Line Size 268 • Brush Shape 268 _ . n„l,.^«„ diAca 974. . Edit Pattern 268 • Polygon Sides 274 • Draw Filled 274 • Draw Centered 274 • Draw Multiple 275 Chapter 16 Painting Strategies 277 h . Borrowing from Others 277 • The Sequence , ^ of Things 278 - To Menu or Not To Menu 279 vi Chapter 17 Building a HyperCard Stack 281 , r< - ! Overview 281 • Part One: Creating the New Stack 284 • Part Two: Modifying Back- ground Graphilcs 293 • Modify Background Fields 316 • Delete Background Buttons 321 • Add Background Buttons 321 • Making the Cards 328 • Using the Stack - •;: 337 PART THREE • HyperCard's Programming Environment 339 Chapter 18 Introduction to HyperTalk 341 ^ . . , ,., Programming and Personal Computers 341 ' " • HyperTalk. The Language 345 • What You Can Do with HypeiTaUc 346 • What HyperTalk Cannot Do 347 • HypeiTalk Modularity 348 • Using the Script Editor ^ , ^ 349 • Structure of a Script 350 • Pieces of ' a HypeiTalk Script 352 • The "It" Local Variable 364 • Other Terms 365 • For- eign Language HypeiTalk 366 Chapter 19 Messages, Hierarchy, and Inheritance 367 ; . Messages, Again 367 • Hierarchy 368 Message Entiy Points 376 • System Mes- sages 383 • Where to Place Message Han- ' dlers 393 • External Resources 394 • In- heritance 395 ',} Chapter 20 Introducing HyperTalk Commands 397 , , Notation Conventions 398 • Containers 400 • Container Components 402 O.-*- ...... ■ ■. i.: vil Chapter 21 Navigation Commands 407 .f Go 407 • Find 409 • Push 411 • Pop 411 • Help 413 Chapter 22 Action Commands 415 Put 415 • Get 419 • Delete 420 • DoMenu 420 • Wait 422 • Dial 424 • Send 427 • Do 428 • Choose 429 • Click 430 • Drag 431 • Type 433 • Sort 434 • Open 436 • Open Printing f;o'; , Print 439 • Close Printing 439 Chapter 23 Arithmetic Commands 441 Add 441 • Subtract 442 • Multiply 444 • Divide 445 • Convert 446 Chapter 24 Object Manipulation Commands 449 '^^ ° Hide 449 • Show 451 • Get 454 • Set 454 • Global 457 • Edit Script 458 Chapter 25 Screen Manipulation Commands 461 '■''^■'^ Visual 461 • Answer 463 • Ask 465 • Ask Password 465 Chapter 26 Sound Commands 469 Beep 469 • Play 470 " ' j^-, CP':.; y,': ' Chapter 27 File Manipulation Commands 475 Open File 475 • Close FUe 475 • Read 476 • Write 478 • Print 480 Chapter 28 HyperCard Properties 483 ^v-.sii i i ;c Global Properties 484 • BlindTyping 484 • ;>JhM Cursor 485 • DragSpeed 486 • EMit- ^ Bkgnd 487 • Language 487 • LockScreen 488 • NumberFormat 489 • PowerKeys 490 • UserLevel 491 • Window Properties 492 • Location 492 • Rectangle 493 • Visible 494 • Painting Properties 494 • Brush 494 • Centered 495 • Filled 495 • Grid 496 • LineSize 497 • Multiple 497 • .;i , :»in MuUiSpace 497 • Pattern 498 • PolySides : . 499 • TextAlign 499 • TextFont 499 • TextHelght 499 • TextSize 499 • TextStyle 499 • Stack, Background, and Card Proper- ties 500 • Name 501 'Script 502 • Field Properties 503 • Location 503 • LockText 504 • ShowLines 504 • Wide- . Margins 504 • Name 504 • Rectangle 505 • Script 506 • Scroll 507 • Style 507 • TextAlign 508 • TextFont 508 • TextHeight 508 • TextSize 508 • TextStyle 508 • Visible 509 • Button Properties 510 • AutoHillte 510 • ShowName 510 • Hilite 510 • Icon 511 • Location 512 • Name 513 • Rectangle 514 • Script 514 • Style 515 • TextAlign 516 • TextFont 516 • TextHeight 516 • TextSize 516 » TextStyle 516 • Visible 517 Chapter 29 Introducing HyperTalk Functions 519 Functions 520 • Using Functions In Scripts 520 Chapter 30 Time and Date Functions 523 * The Date 523 • The Abbreviated Date 523 • The Long Date 523 • The Tune 524 • The Long Time 524 • The Seconds 525 • The Sees 525 • The Ticks 526 ix ;'j:yt -4 * i Chapter 31 Keyboard and Mouse Functions 529 - - TheMouseH 529 • The MouseV 529 • i:' ii • The MouseLoc 529 • The CommandKey Tx^i : -1 531 • TheOptionKey 531 • The ShiftKey 531 • The Mouse 534 • The MouseClick 534 • The ChckLoc 535 Chapter 32 Text Functions 537 s'>5 :8 > / « • The Length 537 • Offset 538 • The Num- • f '^i^ ber 540 • The ChaiToNum 541 • The -? V » NumToChar 541 Chapter 33 Math Functions 545 The Random 545 " The Value 546 • SANE Functions 548 • Abs 548 • Annu- ity 548 • Atan 549 • Average 549 • - Compound 549 • Cos 549 • Exp 549 • >i) Expl 550 • Exp2 550 • Ln 550 • Lnl 550 • Max 550 • Min 550 • Round 551 ' • Sin 551 • Sqrt 551 • Tan 551 • •• Trunc 551 Chapter 34 Miscellaneous Functions 553 , The Number of Cards/Buttons/ Fields 553 " The Result 555 • The Sound 556 • The 9.1c fr Target 557 • The Param 558 • The ^ ParamCount 558 • The Params 558 • .^Hjrrj?. , f{ 3. User-Deflned Functions 561 Chapter 35 Mathematic Operators 563 Plus 563 • Minus 564 • MulUply 565 • Divide 565 • Is, Is Not 566 • Comparison > £c 567 • Dlv 568 • Mod 568 • Miscellane- ous Operators 570 • And 570 • Or 570 . Not 570 • Concatenate 572 • Contains 573 • Is In 573 • Comment 574 • Prece- dence 575 Chapter 36 Constants 577 , , ;:,r;.t True 577 • False 577 • Up 577 • Down 577 • Empty 579 • Quote 579 • Return 580 • Space 580 • Tab 580 • FormFeed 580 • LineFeed 580 Chapter 37 HyperTalk Control Structures 583 , - If-Then Decisions 584 • If... Then 586 • If... Then... Else 587 • Nesting If-Then Deci- sions 589 • Repeat Constructions 590 • Repeat For 590 • Repeat Until 591 • Repeat While 592 • Repeat With 593 • , ^ ,, Modifying Repeat Execution Order 594 • Next Repeat 594 • Exit Repeat 595 • Exit If 595 • Exit 595 • Pass 596 PART FOUR Applying HyperCard and HypefTalk 599 Chapter 38 Introduction to Applications 601 5''. .v4_, , A Useful Utility Script 602 Chapter 39 A Corporate Directory 605 i Overview 605 • Scripts and Properties 608 ' '^J'^^ • Further Ideas 615 Chapter 40 A Telephone Logbook 617 Overview 617 • Scripts and Properties 619 . ' • Further Ideas 624 -v- >; - 0 Chapter 41 A Time Sheet 625 fyjf - . , Overview 625 • Scripts and Properties 627 r '^- g • Further Ideas 633 Chapter 42 A New and Improved To Do List 635 oQ • K\A qV Overview 635 • Scripts and Properties 638 • Further Ideas 649 Chapter 43 A Conversion Calculator 651 Overview 651 • Scripts and Properties 654 • Further Ideas 662 Chapter 44 A Visual Outliner 663 ' *■ -t&f-m >. Overview 663 • Scripts and Properties 667 • Further Ideas 682 • A Final Note 683 PART FIVE , ,j HyperCard 1.1 and 1.2 685 Chapter 45 Making the (Up)Grade 687 The Importance of Upgrades 687 • Update Chronol- o^ 688 • Hovir to Upgrade 692 Chapter 46 New HyperCard Features 697 ^'^'^^ TextArrows Property 697 • HyperCard and Multl- Flnder 699 • New Find Commands 700 • Auto Tab 702 • Keyboard Shortcut Change 705 • Working with Write Protected Disks 705 Chapter 47 New HyperTalk Features 707 , / Abbreviations and Synonyms 707 • Two Old System Messages 709 • New System Messages 710 • Key- board Shortcuts 713 • Peeking at Objects 713 • S'lU r Peeking at Scripts 714 • Testing for the HyperCard Version 716 • Locking and Unlocking Screens 717 xli , i ;iKf'. * • Target and Me 718 • Other Improvements 718 • Bug Fixes to HyperCard 1.2 721 • XCMD Enhance- ments 722 Chapter 48 HypeiTalk Expressions 725 . ..... Everyday Expressions 725 • Expressions in Hyper- » r58t y-.: • Talk 726 • Evaluating Expressions 727 • Expres- sion Types 728 • Expression Notation 732 • "Do" and Expressions 732 Chapter 49 HyperTalk Commands Update 735 Exit to HyperCard 735 • Reset Paint 737 • Select 738 • Select 740 • Hide 743 • . , ; . Show 743 • Lock Screen 744 • Unlock Screen « - : 744 • Find Whole 746 • Find String 746 v Chapter 50 HyperTalk Functions Update 749 The HeapSpace 749 • The StackSpace 749 • The - DiskSpace 750 • The ClickH 75 1 • The CllckV 751 • The SelectedText 752 • The SelectedChunk if^fc 752 • The SelectedUne 751 • The SelectedFleld • " 751 • TheFoundText 754 • The FoundChunk 754 ' ' . , • TheFoundLtne 754 • The FoundFleld 754 • The Number of Cards of 756 • The Ver- i slon of HyperCard 757 • The Long Version of , HyperCard 757 • The Version of Stack 757 • The ScreenRect 759 Chapter 51 HyperTalk Properties & Operator Update 761 « i I..-;: LockMessages 761 • LockRecent 762 • Size 763 ..'V': • FreeSize 763 • Left 764 • Top 764 • Right 764 • Bottom 764 • TopLeft 764 • BottomRight 764 • BotRight764 'Width 764 • Height 764 • Cursor 766 • CantDelete 767 • CantModlfy xiii 768 • UserModiiy 769 • AutoTab 770 • ShowPlct 771 • Within 772 Chapter 52 New HyperTalk Features at Work 775 Search-and-Replace 775 • An Efficient Spreadsheet ,5,;yH 779 • Multiple Scrolling Fields 780 • Field Bugs .^c kJ ^ -< 785 • Turning Lines into Spreadsheet Cells 786 • 'oO- *^ i:l Adding it All Up 789 Chapter 53 Using HyperCard on Locked Media and Networks 791 ..^^ , What Exactly is CD-ROM? 792 • CD-ROM and HyperCard 793 • Getting a Stack onto CD-ROM 794 • HyperCard on a Network 794 Chapter 54 Introduction to External Resources 799 - -i > Resources- the Building Blocks 799 • About ResCopy 800 • Resources and Copyrights 807 Chapter 55 Interpreting "HyperCard Helper" Messages 809 Appendix A Tips on Importing and Exporting Data 835 Text Transfers to HyperCard 835 • Export- . ingText 836 • Graphics Transfers 837 Appendix B HyperCard 1.2 Quick Reference 839 w v-''^-' Index 849 ' * ' " xiv Acknowledgments Although I use many metaphors throughout this book to describe various aspects of HyperCard, I'd like to use a HyperCard metaphor to thank the many people who made my pELrtlcipation In this important project possible and so rewarding. You'll pardon me, then, as I choose Recent from the Go menu to review In historical order the faces of those who played key roles. In the very first position is Jane Anderson. While my contact with her was for other Apple-related purposes, Jane ultimately became the critical link to the rest of my journey with HyperCard. Next in the Recent dialog is John Sculley. For reasons still unknown to me, he took me into Apple's confidence early in 1986 and revealed the wonders of HyperCard, while suggesting 1 write a book on the product. He was also kind enough to contribute the Foreword. If the Recent dialog box showed a minicard for each visit to that card, the dialog would be almost completely filled with Bill Atkinson cards. The experience of watching him for a year and a half mold HyperCard into its present shape has been a privilege I will never forget. He instructed me, he listened to what I had to say, he made me feel very much a part of his vision of Hj^perCard. Next comes Chris Espinosa, who had to put up with many hand- wringing messages and conversations as various deadlines came and went. He was far more supportive of my "outsider" HjrperCard efforts than I thought possible. As I near the end of the Recent dialog box, I see the friendly face of Dan Winkler. As the caretaker of HyperTalk In Its development, he volun- teered a great deal of extra time to check the HyperTalk parts of this book for accuracy. He turned HyperTalk scripts for my stack applica- tions in Part Four into some of the cleanest, most elegant HypeiTalk code 1 can imagine. I also wish to express gratitude to Olivier Bouley, Ted Kaehler, and Julie Lieber at Apple for giving my projects special attention. My thanks also go to Kenzl Sugihara and Jono Hardjowlrogo of Bantam Books for their faith in my early estimate of HyperCard's importance to personal computing. To my many friends and colleagues who couldn't get me to reveal the Big Secret for such a long time, well, This Is It. Thanks for putting up with my tight-lip policy. Finally, I'm lucky to have a place here to express my appreciation for Linda's love and understanding over the last ten- plus years of our life together— so much of which I've spent putting words to disk. Your eternal patience is a great comfort. Foreword John ScuUey Chairman and CEO Apple Computer Inc. Hypermedia. It's a new word for most of us. Yet this term and its defmition will become increasingly Important the more we rely on personal computers to store, manage, and retrieve information. In broad terms, hypermedia is the delivery of information in forms that go beyond traditional list and database report methods. More specifically, it means that you don't have to follow a predetermined organization scheme when searching for information. Instead, you branch instantly to related facts. The information is eternally cross- referenced, with fact linked to fact, linked to fact. Hypermedia is particularly true to its name when it links facts across conventional subject boundaries. For example, when studying chem- istry, you may wish to study the life of a chemical compound's creator. One hypermedia link would connect that compound to the chemist's biographical information located in an entirely different reference work. Another link might connect the chemical compound to a listing of grocery store products that incorporate the compound, or to long-term health studies on the compound. We can focus more on content, while ignoring the organization. Until recently, there has been little need to address hypermedia on personal computers, largely because of the limited amount of informa- tion most computers could manage "on line" at any one time. But as high capacity magnetic hard disks become nearly standard equipment on computers like the Macintosh, established methods of finding related pieces of information become cumbersome. At the same time, we've scarcely begun to take advantage of new magnetic and optical mass storage technologies that place on our desktops more information than the largest mainframe computers managed ten years ago. xvii The hardware that holds the information is only one side of the hypermedia equation. The balancing side- and unquestionably the most difficult part- is the software that lets us function in a hyperme- dia environment. By "function," I mean working with Imked informa- tion in an Intuitive and Interactive way. And not putting information delivery just into the hands of computer professionals, but giving everyone sufficient power to bring Information to life. BUI Atkinson's HyperCard puts hypermedia into the hands of nearly every Macintosh owner. I should stress that HyperCard is not an application, like a word processing, spreadsheet, or database program. It is, rather, a software engine- a hypermedia toolkit, if you will. With HyperCard, virtually anyone can become a software author, producing an information- based application that looks like a professionally designed Macintosh application. HyperCard is also like a tape player on which you run HyperCard applications written by others. The key to HyperCard's authoring environment is HyperTalk, a mar\'elously simple programming language built into the engine. Within a very short time after HyperCard's release, 1 foresee the development of thousands of applications not now available on the Macintosh. These applications vrfU not come from the ranks of experi- enced Macintosh programmers, but from non-programmers who are otherwise intimidated by the complexity of serious programming. Danny Goodman, the author of this book, is a case in point. Over the course of several years, Danny developed in his mind's eye a dream application to help him manage his time, writing projects, and deadlines. Even though he had a firm idea of what the program should do, Danny didn't have the time to master computer programming to make his program do what he needed. E>ven the relational database programs for the Macintosh didn't offer the flexibility he required. But working in the Hj^erCard environment, Danny was finally able to turn his dream Into a practical program. Then he discovered that other people liked it as well. Thus was bom Focal Poinf*^, one of the first third-party stackware products. This story wiU be repeated by many authors for many applications In the years ahead. This, I believe, is a major strength of HyperCard: it shatters the barrier between a person's information handling dream and its realization. The expertise embodied in HyperCard applications will be the expertise of buslnesspeople, professional people, and educators- in short, the people who work with Information daily. Information publishing may also take a new turn with the advent of HyperCard. Since HyperCard is ready today to act as a familiar "front end" to mass storage devices like CD-ROMs, interactive videodiscs, and future optical storage technologies, anyone with information to distrib- xvlli ute can design toward a unified software Interface for all Macintosh models. Once a user has access to this information, HyperCard stacks are empowered to work far more interactively with the information than the traditional "search and sort" routines of a read-only database. Potentially, HyperCard can be as important for the Macintosh in the late 1980s as Applesoft BASIC was for the original Apple II in the late 1970's. Applesoft BASIC allowed dedicated enthusiasts to put a new computer technology to work for them. HyperCard puts far more powerful tools into the hands of virtually everyone who knows how to use a Macintosh. Like so much of what we at Apple have been doing for our first decade— enabling people to use personal computers produc- tively—HyperCard in our second decade presents a new software technology platform on which many more people can build. HyperCard and the wonderful opportunities It presents for personal computing would not have been possible without the genius of Bill Atkinson. When I first saw a prototype in late 1985, it was clear to me that BUI was brewing a software revolution. Since then, he has solved enormous technical difficulties and added more features and ease of use than anyone thought possible. In the land of Apple Computer, Bill Atkinson is a national treasure. Now that the IBM compatible world recognizes the Macintosh human Interface style as a mainstream idea- and a desirable idea at that— Apple Computer must push even harder to maintain meaningful differences between the IBM and Macintosh worlds. I believe Hyper- Card stands as a perfect example of Apple's commitment to that goal. xix A Conversation with Bill Atkinson Bill Atkinson, the creator of HyperCard, took time out during the last weeks of HyperCard development to talk with me about many issues surrounding the program's development and his aspirations for the product. The interview took place in what I would call a HyperCard community: his home in the hills at the far south end of the San Francisco Bay area. As he and I talked into a tape recorder in one part of the house, Dan Winkler, Bill's chief co-programmer, was in another part of the house making the HyperTalk language work faster. In yet another room. Marge Boots, a Macintosh artist, was busy exploring card and icon designs that would be included with the program. It was Memorial Day, but when Apple deadlines approach, it's "business as usual" seven days a week at this HyperCard colony. Danny Gckjdman: A lot of people have different ways of describing HyperCard. How do you describe HyperCard? Bill Atkinson: HyperCard is an authoring tool and an Information organizer. You can use it to create stacks of information to share with other people or to read stacks of Information made by other people. So it's both an authoring tool and sort of a cassette player for Information. Goodman: Where did the idea for HyperCard come from? , ,,,,j^f, Atkinson: There were a lot of roots to it. One of the early contributors was the Magic Slate project that 1 worked on for a while, but that was later cancelled. Magic Slate was a laptop computer that had a full-page display and an all -graphical interface. We worked out some neat paradigms for breaking down the barriers to applications. xxi Goodman; Why was Magic Slate dropjjed? Atkinson: It couldn't really happen in a short time frame. It wouldn't be cost effective for a lot of people. It would be too expensive for many people to get their hands on it. Goodman; What happened then? ^ ' "'' i t ".f-r ..r.i. , Atkinson: So I backed down to saying, "How much of what IVe learned or dreamed about here in Magic Slate could 1 do on today's generation of computers?" 1 started thinking that many more people would have a use for a computer if it did some different things than it does now. Right now, they're used mostly for word processing and spreadsheets and, I guess, lately, some graphics applications. But, I thought, in order to use one of those applications, you have to see yourself as being a creator of information. What do you do about the consumer of information? There are maybe twenty times as many people who want to read information. Goodman: Was that a major turning point? Atkinson: That's when I started thinking about gradually unfolding a path that starts with clicking and browsing— something that anybody could do and that would be useful for a lot of things. Then up to some painting, which Isn't that much harder if you've used something like MacPaint before. And then onto cutting and pasting buttons and making some authoring tools In a kind of erector set approach. You're really making a program. But you're making it Just by cutting and pasting little pieces. And then, finally, all the way up to teaching what I do, which Is programming. The HyperTalk language is sort of a humane starting language for people who want control of their com- puter. They are not interested In programming per se. The language is something that can be a good first introduction to programming and will provide enough power that most people don't have to go into Assembler language and what not. Goodman; HyperCard seems like many different programs in one. You have a graphics program, you have a programming environment, and you have the ability to do a lot of things with those tools. Atkinson: A lot of its multiple facet is because you're looking at things made with HyperCard. The HyperCard program itself is an authoring tool, but the things that it creates are applications in their own right. So you look at HyperCard as it conies. It comes with an address book and an appointment calendar, and a dozen stacks that are like applications. One part of the multiplicity comes because you're looking at some sample tapes that came with your cassette player. The other part of it is just that it is an authoring tool, with graphics and text intermixed. Goodman: From the authoring standpoint, when someone looks at the manual that comes with HyperCard, the program doesn't seem that complex. But then they heft this rather thick book and they see an enormous program with a lot of depth. Is that going to frighten some people away? Atfonson: Well it's very important that one's first Interaction with HyperCard be a positive experience. You've got to have success right away or you'll never go on to growing into some of the more powerful features. That's why, in fact, I've gone to great lengths to hide some of the power In the early stages. It's like prerequisites for courses In college. In the same way, I hope that beginners can come into this with the idea of, "Well, I can Just click to browse around, and I can click and type to add cards," and they can use it right away. There are a number of good strong resting points that let you say, "Okay, I understand browsing now," or "I understand typing now, and I can rest there for a whUe. Later I'll learn how to work all the painting tools." Even in the language, when you get more Into HyperTalk, there's this gentle gradual progression from tjrplng things Into the Message Box. You type 5/6 and press Return, and It calculates some number. And you say, "Okay, that's not much harder than a calculator, 1 think I can figure that out." But then you can type little things like go "Clip Art" and you learn that whatever command you type In there HyperCard will do. You learn one little step at a time. You say the date, carriage return, eind there's today's date. You leam that before you learn about put the date intofield 3. And you leam all that before you leam, "Oh you can get other things to type in these commands for you." Goodman: How long have you been at HyperCard? Atkinson: About two and a half years, almost three. Goodman: Over that time, how have the basic features of HyperCard evolved? How have they evolved from your original plan? xxiil Atkinson: My initial mockup was done with MacPaint documents and a text file that described the relationships between them. A button would have three attributes basically: a visual effect, a sound effect, and a destination. And that was Initially all the buttons could do. But there was no language, because It was Just a matter of choosing which of those attributes you wanted. But still the very quick branching from one place to another by touching hasn't changed much since then. The card size changed. It used to be the same size as a MacPaint window, which is about one-half of the area of the card we're doing now. As HyperCard became more of an authoring tool, it became obvious that people really needed to be able to take over the whole screen, including the menubar, in order to control the complete look of what their application behaved like. Goodman: Didn't you have some breakthroughs in handling graphics? Atkinson: It went from being the card-specific graphics just being OR'ed on top of the background— where all you could do was add more black bits: You couldn't add more white bits- to a strategy of actually having mask and data so that the bit maps are all two bits deep and you can have opaque white. That was a major step and a major hurdle to get over. That was the point when I had to come up with the bit map compression because things Just got totally out of hand. But I really wanted the flexibility and artistic abilliy of bit maps rather than using structured graphics, which Just couldn't express the richness that I want for a user Interface. At one point, there were two completely different envlroiunents. There was the painting environment and the authoring environment, and I literally bank switched a whole hunk of code out. another hunk of code In. Those two were not integrated at all. They were very, very different palettes and very different behaviors. We've worked a lot toward Integrating them now so that going back and forth Isn't so painful and it's much more integrated. In fact, the latest stages of integration, as one of the last things along that line, is this business about actually being able to control the painting tools from the language, which gives a tremendous power for its memory cost. Now you can algorithmlcally compute things that you want to draw: charts and drawings and various plots and stuff like that. Goodman: Any other evolutions? Atkinson: When we went to full size and mask in data, there were big performance hits. Suddenly things got about fifteen times slower than xxiv MacPaint, and I had to figure out some whole new algorithms and ways to handle that. In fact, I took a room at a hotel near the beach and just camped out there in seclusion, away from anybody else, while I cracked getting the graphics stuff working. That was pretty nice when I got that working. Goodman: For the painting tools, then, you've done far more than just cany over the MacPaint code. Atkinson: You bet! It has disapointed me how little other programmers have done with the additional RAM that they've got. A lot of the shortcomings of MacPaint were strictly because 1 had to squeeze it Into 1 28K bytes, when there was 22K of that on the screen and another good chunk in the system heap. But the whole resident code for MacPaint was 25K bytes. The resident code for HyperCard is more on the order of 250K. With more code. If you have more memory, you can do a lot more. Some of the things I wanted to do in the original MacPaint I was able to do here, Uke having infinite Undo, and being able to select the last thing you just drew. They seemed like obvious things to me, and I don't know why other people haven't done them. Being able to operate on a lasso selection as a first class citizen means that you can really do everything to a lasso selection that you could do to a rectangular selection. It costs memory when I'm in the Painting tools. It costs me seven additional buffers, each of which is the full size of a card. So seven times 22K on top of the six buffers that 1 norniEilly have, that's where a lot of the memory is going. But these days, memory is cheap compared to the power that it gives. You can get a non- Apple upgrade from 512K to a megabyte for something like $200. If you were to buy a program for $200, you wouldn't be that put out. But I have really struggled trying to get this thing to run on a 512, not because of the cost, but because of the number of machines that are out there that are still 512s, and the hassle of going in and getting it upgraded. 1 just wasn't able to do it for the painting tools. 1 may stUl be able to do it for a browse-only kind of thing, Goodman: As far as the functionality of the program goes, has the function or the scope of the program changed over this period, in light of the way the Macintosh has been accepted or perceived by different categories of users? Atkinson: Not because of what's happening with the Macintosh, but it certainly has changed a lot. The Initial Intention was for It to be an authoring system, but not necessarily a programming system. Through XXV HyperTalk, it has really gained much more generality and has became much more of an erector set for building applications. Goodman: For the programmers in the audience, how was your software development environment different for HyperCard as compared to MacPaint? Atkinson: Well. I wrote MacPaint on a Lisa. 1 compiled and ran on a Lisa on a Profile. I would always then download to a Macintosh and try it. The first year and a half of doing HyperCard. I did on a Mac Plus with a hard disk. And that was pretty nice that I could actually take my whole working environment with me to a hotel and hide out there, because all I needed to take was a hard disk and a Mac. Then I got hooked on this faster Mac 11 prototype that cut my compUe time. As the program got bigger, a forty-five minute compile was a killer. If I could cut that down to about six minutes, then I figured I'd marry myself to the big clunker. Goodman; What about the personal environment? Atkinson: Well, when I was working on QuickDraw, that was all mine. I wrote it all myself I didn't let anybody look at my sources. I listened to what people needed in the labs, but it was my call on everything. Then I went from that to MacPaint, which was more of a shared thing, because I would accept a lot of kibitzing from people who would use it as I was developing It. Stm. 1 wrote every line of code. Nobody saw the source until after we had shipped. What I'm finding with HyperCard is that this trend in the way I work is progressing. I'm working more with other people. There are twenty people who've got their fmgers in the pie on HyperCard. There are four that are writing serious chunks of the code. It's still basically my baby. I insist that everything be right, and I read all the code. I probably have written 70 percent of the code that's in there. Dan Winkler is the next major contributor to the code. 1 needed somebody who could keep up with me, who would go with my style. Dan was willing to learn from me and pick up my style. We work back and forth, we hand code back and forth. We both work here at my house, and I see, in general. I'm able to accomplish a lot more by working with other people. That's good because I think what HyperCard is all about is sharing information. A program's soul has a lot to do with the people who are making it and what they're thinking about as they're making it. We're not making this to make money. We're not making this to make Apple happy. We're making this because we want to share something. One of xxvl the things that I find myself sharing is my understanding of program- ming. I find that I'm a very good programmer and that I know something about computer graphics. Those two things I think I can teach by example in HyperCard. Goodman: HyperCard was almost not an Apple product. What's the real story behind that? ATfUNSON: Well, Apple has felt a lot of pressure from third-party developers to not ship application software because it competes with the third-party developers. And there are aspects of HyperCard that are appUcation-llke. it comes with an address book. That's like an applica- tion. There are other aspects of it that are clearly a tool to build things with— the authoring aspects of it. But as Apple saw it as potentially application-like, there was this big question: If Apple sees Itself as system software people and this thing is somewhere between system software and application software, what happens to it? This came up at the time that they unbundled MacPaint from inside the Macintosh box. After telling me, "Don't worry, we're not going to unbundle it." and then telling me, "Oh, it's too late, it's fait accompli now," I felt that somebody wasn't dealing with me fairly. The relation- ship that I had with Apple was going downhill fast. I have a very special relationship with Apple, it's a relationship of trust and cooperation. I need them and they need me, but it's never been one of an arms-length contract relationship. I don't work very well that way. I'm not good at that kind of thtng. 1 like to work with people who are rooting for me and helping me. So at a certain point 1 said, "I see you unbundling MacPaint. I see Donn Denman. who wrote this beautiful BASIC for Mac, not being able to publish his beautiful work that he put three years into." I could see something coming for H3rperCard. I went to John Sculley and said, Tm leaving. 1 have to leave Apple at this point because I want to write a really great program for Macintosh. I can do Apple a lot of good, but I want to make sure that it gets out." John was very supportive, and was enthusiastic about the potential of HyperCard. He talked It over with the executive staff and let me give a presentation. I said, "What I want is to bundle it. If you want to bundle it, I'll write It for Apple. You can have the exclusive proprletaiy rights and all that stuff, but tf you don't want to bundle It then it's time for me to graduate from Apple and go on and be an independent developer myself. I'm going to get this out to people whether I give it away or whether I get Apple to give it away." To this day, Apple is not required to bundle it. They only have an option that if they choose to accept it, then they have to bundle it. TTiey could say no to me right now, but at least then its ownership xxvti reverts to me so that I can give it away, which I would do. You see, I want it to be given away so that it can be a base for people to share. What I will be really excited about is the stacks that come back to me that other people have done. The Apple 11 when we first put it out was sort of a wrench that we didn't say what it was good for. People would use it for the most amazing things. We'd be kind of flabbergasted when we'd see this Apple II controUing some oil drilling rig. I think that HyperCard has that same flavor to it. The reward of sharing it will come right back and 1 will get amazing stacks from people who have information but don't have the tools to get it out now. Goodman: If you were a software reviewer in the magazines, what would you try to compare HyperCard to? Atkinson; HyperCard is an authoring tool, and as such I would compare it with authoring tools like Owl's Guide, like Plato, like Pilot, like Logo. Those are the fairest comparisons, I think. It's an authoring tool. It's kind of a personal organizer, too, but that comes as a result of the authoring tool rather than as the motivating factor. You can use it as a hub for launching documents and applications. In that sense, it's almost like a Finder. Goodman: Where do you think you'll find these people starting to apply it first? Where do you expect the first applications? Atkinson: Education will pick It up right away. There is a growing number of Macintoshes in lower education, but higher education already has lots of Macintoshes and it's so easy to whip together a teaching application. Goodman: What kinds of things do you expect them to be doing? Atkinson: For example, in the Exploratorium Science Museum in San Francisco, I would expect them to be using Macintoshes and Hyper- Card to give hands-on interactive demonstrations of physics principles they are trying to teach, where you poke at something and try this, sort of a little HyperCard lab. The people at Stanford have been a very early seed for HyperCard. It's being used in a film-editing class where they go out with a video camera and shoot all the scenes for a movie. Then they put them on a video disk. Students come in and use a HyperCard stack that has a stoiyboard. one little miniature picture for each sequence that was shot. They buUd the movie out of it. You splice it and lay it together by touching on things xxvill In HyperCard and play it back and edit It, make this shorter or make that longer, or move this scene out of here and put It over there. The end result Is that each student has a diskette with a HjrperCard stack on it that represents his editing of that film. Nobody's ever had to actually get his hands wet in a darkroom or do any acetate-spUcing or videotape-editing and everybody's got the same stuff to work with, so you're concentrating on the editing job rather than the cinematog- raphy. Now it's very interesting to see the different renditions different people can come up with because of their own artistic tastes. You can take the same raw stuff and come up with very different pieces based on it. Goodman: Let's move on to HyperTalk. Programming languages all seem to come down an ancestral path. What are the language ancestors of HyperTalk? Atkinson: The first one is English. I really tried to make it English-like. It also borrows some concepts from SmallTalk— the inheritance con- cepts. If you send a message to the card and the card doesn't understand It, it falls through the background of it. If the background doesn't understand It, it falls through to the stack, and if the stack doesn't understand it, it falls through to HyperCard. That inheritance is similar to what they have in SmallTalk. HyperTalk has some background in Pascal Just because that's what I speak a lot of. HyperCard itself is about 80 percent Pascal and 20 percent Assembly language. Goodman: How did HyperTalk evolve? /. Atkinson: Hie first design of the HyperTalk language I did in a five-day period. I had an outline that's still basically what it does now: the way you name things— buttons, fields, cards, backgrounds, stacks, the Home Stack— and they way you name things— card one, first card, last card, any card- those kinds of things. Then Dan Winkler came into the picture. He took this rough mockup and breathed life Into it and made it real. He's developed a full language out of it, and we worked together back and forth, kibitzing a lot. But Dan has certainly done the bulk of the work of making it real. He's done a lot of thinking on how to implement it well and how to make it cleanly organized inside. Goodman: Who were some of the other key players on Apple's HyperCard team that helped put HyperCard together? xxix Atkinson- Ted and Carol Kaehler were really big players. Carol did the on-line help system. Here was an author, not a programmer, who in the course of working with HyperCard, had to use all the features. She had to become a HyperCard programmer. I often find that 1 design by pull, m the HypeiTalk language and in HyperCard, the capabilities were really determined by what people wanted to do with it, so Carol has been a big pull there. , 4. u Ted has been kind of a kibitzer to me. We talk algorithms and we talk about what we reaUy want, and stuff like that. Adam Paal has been a malor contributor. He's been Mr. Printing and has solved the reaUy difficult problem of how to get a LaserWriter that's running Adobe software, which doesn't like bit maps, to not only take bit maps, but go quickly He's dealt with that, he's dealt with, weU, what are the different ways that people would like to print the stuff. It would be safe to say that I wrote all of HyperCard except for the language and the printing and the sound manager. The language is Dan's, the printing is Adam s, and the sound manager is Ted's. - That's the breakdown of who contributed to the code. Lots of people contributed to shaping it. You know, 1 asked people what they wished they had.The biggest thing is to get people to try to build something with it. Then they run Into what they really need, not just what they think they need. Goodman: Was anybody at Apple running interference for you while you coded? Atkinson: Yes. Chris Esplnosa has been a godsend. He's my product manager and he's been with Apple for a long, long time. I think I ve been there nine years and he's one of the few people who has been there longer. I've worked with marketing types before, and it's always grating because they didn't understand the technical side of things. Chris has been real good and he "gets it." He really sees what HyperCard cari do for the world. And there aren't enough people at Apple who see that. They may see It more as it gets out and as people start doing stuff with it and they start reaping the benefits, but Chris really has that vision and can see what HyperCard Is going to do to people's lives and to Apple's future. ^ Goodman: What parts of HyperCard are you most proud of? - Atkinson: WeU, I'm really proud of the fast search. I worked out a way to make searching about 200 times faster than a more obvious way. 1 m proud of the bit-map packing. Bit maps are packed about 30 to 1, and XXX it's really tough to get them that tight. The dominating factor in the size of stacks is how big the bit maps are. So it's something I'm always chewing on in the back of my mind: Is there a way to get the bit map smaller? Overall, the thing that I'm most excited about in HyperCard is its "opening up" potential. You know, we talk about open architecture hardware. Well, this is open architecture software where, really, you can go inside a stack that somebody else wrote and look and see how it was done and modify it and tweak it a little to tune it for your uses and learn from what someone else has done. : --m , . i.u .in, Goodman: What's the chance that someone from the MS-DOS or OS/2 worlds will replicate HyperCard? Atkinson: Oh, 99 percent. Something like that. I think it's a good enough tool that people will say, "Of course," and start working on clones. It will take them a while to get anything as smooth. You know, I've had a couple years jump on them. When that starts to happen, 1 hope that they'll do one that's data compatible, so we can exchange stacks between "PC Card" and HyperCard. To that end, we intend to make all the file formats public. We won't actively go out and help people get it up on the PC, but we're fielping them an awful lot just by giving all the details of the file format. I'd like to see Apple get an edge, but I'm really more interested in the worldwide sharing of information. That will happen much better if there is a compatible program on all the different machines, I'd like to see one on the Apple II, which doesn't have any conflict for Apple, and so I will be helping a programmer at Apple make an Apple 11 version of HyperCard, -.^■■^^ - i Goodman; Is there stUl a lot of proprietary technology built into Hyper- Card? - .V ..• H!.., -, >. :..-:.-■:<., ' ^ ^ : ; ^ Atkinson: Well, what's proprietaiy? You know, you get a great idea, you use it. There's no idea that's totally original. The question is, can you get a patent on it? Sure, there's stuff in there we could easily get patents on. What's really right in terms of your long-term goals? What are you trying to do? Yes , we want to keep Apple in business so they can do other great stuff, but we also want to make an environment for sharing. Goodman: Do you have future plans for HyperCard? Atkinson: Oh, do I have anything else? Yes. I have many, many future plans, I've got a big laundry list of features. 1 know what they all are, and I know which ones are most pressing. I'd rather not tell everybody what xxxi they are because I want to have a little bit of Jump when those features come out, Goodman: But we can expect to see additions? Atkinson: Lots of improvements. This is not going to be abandoned like MacPaint was. Pretty much Apple put me on something else and gave the maintenance of MacPaint to someone else and then kept shuffling that from one person to another, and MacPaint never got maintained. My full-time schedule for the next couple years is Improving Hyper- Card. I have a lot in front of me that I need to do. 4li *^>f! ■ A xxxii How to Use This Book 1 .. . By now, you have probably started HyperCard at least once to see what It is all about. Some of the HyperCard applications delivered with the program have obvious utility for nearly every Macintosh owner— the name and address card file, the calendar, and the appointment book. But HyperCard is far more than these examples demonstrate. So much so that this book is divided into four sections, each exploring additional features and powers of HyperCard. Each section will also bring you to a higher level of HyperCard proficiency. There are few prerequisites for this book. All we ask is that you be familiar with basic Macintosh operations, such as pointing and click- ing, pulling down menus, choosing menu items, and the basic "feel" of the Macintosh Finder. This information is readily available in the owner's manual of the Macintosh model you use. If you are not fully acquainted vrith these concepts, take some time now. Exploring the Finder for fifteen or thirty minutes now— moving file icons around the screen, opening folders, selecting an icon, and choosing Get Info from the File menu— wiU save you much time later when you'll have to call upon that experience. Fortunately, it doesn't take long to become comfortable with basic Macintosh operations. Like HyperCard, this book is structured to let you reach increasing stages of proficiency without having to devour the entire work at once. Move through each part at your own pace. Don't rush it. Most importantly, read this book whUe sitting in front of your Macintosh with HyperCard ready to go. You will learn HjrperCard much faster if you follow the experiments and step-by- step Instructions throughout the book. All in all, it should be an enjoyable experience. xxxUi Preface to the 2nd Edition The release of Version 1 .2 presented an excellent opportunity to update The Complete HyperCard Handbook. The quick acceptance of the First Edition, which became the best-selling Macintosh book ever produced, caught everyone, including me. off guard. It is most gratifying that many experienced HyperCard authors today still regard the Handbook as the primary reference and instructor for the program and the HyperTalk language. In this Second Edition, I have made minor corrections to the First Edition's main text. Some of these corrections appeared earlier, starting with the third printing of the original book. At the end of this edition is an eleven-chapter supplement, which details all new features of HyperCard 1 . 1 and 1.2, plus a few items that crept into HyperCard 1.0. 1 after the Handbook went to press. 1 believe that with this edition, 1 have met the responsibility of the book's title: it is the most complete reference and instructional tool for HyperCard and HyperTalk. As you'll learn in my interview with Bill Atkinson, HyperCard is still under construction. As HyperCard evolves, so wUl the Handbook evolve to match its new powers. The xxxiv INTRODUCTION Coping with the Information Revolution Long before my hands touched a computer eceyboard or my eyes peered into a computer monitor, I saw television advertising for worldwide com- puter companies that talked about "moving Information." The screen showed colorful, mystical interconnections linking New York with New Delhi, via dozens of stops in Europe, Asia, and everywhere. When 1 watched these commercials, I had great difficulty visualizing "informa- tion" and why anyone would want to "move" it. The problem was my failure to understand how all-encompassing the term "information" can be, Eind how many forms Information can assume. Nor, I think, was 1 the only one unsure about what Information is. Our inability to grasp the concept Is largely the result of information's intangible nature. It can be printed, spoken, and drawn, but these forms are mere representations of Information. The marks on a page or screen, the sounds of speech and music— none of this Is Information unless It conveys meaning to yourself or others. Yet human history demonstrates a long-standing need for Information and the skills to manipulate it. The Historical Chain of Information The earliest surviving evidence of information recording (other than the artistic expressions of cave painting) comes from the ancient Sumerian civilization in the Middle East, dating back to 3000 b.c. Clay tablets 1 2 Introduction bearine pictographic impressions of a wedge-shaped stylus record the moment of commodities through the marketplace Unltt^e the ora^ ZSZn. which was responsible for great epic poetry like the stories of Gneamesh and Odysseus, writing provided a medium for accurate and faSSSfoSation'^EvenSOOOyearsago.civllizationand^ pTac^l information burdens on its participants greater than their ability to manage solely by memory and word of mouth. ' Sually, lictographic Indo-European J-S^f f ^^^^ ^^^^ nhonetic languages, in which combinations of alphabet letters spelled ?ut sounds, iritten information spread to include not only business ilsactions but also literature and personal --^-f-^^^f^^^^^ much archaeological evidence from the ancient Egyptian. Greek R^an Si Oriental cultures to demonstrate the growing diversi^ of information through the millennia. INFORMATION'S EARLY SPEED LIMITS The movement of information from person to person, hoyf'e'-. re- mained at the mercy of the transportation systems available. For "entries aJter Gutenberg's printing press S-^^ ^^^1^^^™ traveled no faster than animal- and natural-powered transport. -Hie lecd at which information Oowed. even well into the nineteentii centui^ IS considered intolerably slow today. American fanners In r^raTs^kions of Atlantic seaboard states had no f ^-^^ wy ofknov^^ what the prevailing market prices were for their g^^^s esi^claUy tf those products were purchased by overseas buyers and their agents in the port cities. Information that made the journey back to the farm was TSthtrio— bottleneck, levels of sales yent^^brok^; iobbers wholesalers, and credit systems intervened. Control over iZSTatirn was essentially handed to others who worked closer to wS^the ^formation chiged hands. Cumbersome thou^ it was Ss form of distributed information handling worked adequately in Ite ^^-n time especially since goods themselves moved slowly, drawn overland fToiJfiOT by horse or across oceans by wind-powered sailing ships. THE EARLY INFORMATION AGE in the 1830s, applications of two powerful ^T/J^PX^^ (for transportation and manufacturing energy) and t^J^ ^elegraph siiiadS radical changes in informaUon quantity and distribution, S^lngtocontempofaiy reports Coping with the Information Revolution 3 major cities, steam-powered locomotives increased the throughput of goods three to ten times during the first quarter-century of steam railroads. For example, the trip from New York to Chicago shrank from a horse-drawn three weeks to a railroaded two days. Railroad companies adopted the telegraph as a means of controlling their spreading empires (indeed, most telegraph lines ran along rail- road rights of way). But telegraphy quickly became a major informa- tion pipeline for commercial, as well as personal, data, as goods and people moved through the steam-powered rail and water transporta- tion systems at great speeds and with predictability. With the spread of these transportation and communications sys- tems—infrastructures, they're called— came an Increased need for controlling the systems themselves. Timetables, fee schedules, collect- ing of ticket fees from passengers, monitoring the location of rolling stock, and similar controls became more important as the Infrastruc- tures became larger than one person could manage. The word control Implies that information proceeded outward, from a "central office" to the extremities of the Infrastructure. Actually, control requires a two- way movement of information: control going out and feedback return- ing home as a means of measuring the effectiveness of the outgoing control. This was the beginning of a class of workers whose sole job was gathering and manipulating information, rather than processing en- ergy or materials. As the decades passed into the twentieth century, the spiraling codevelopment of technologies (energy utilization and communication, in particular) increased the speed at which goods, services, and people moved throughout the world. With each Increment of the transporta- tion speedometer came an increased need for control. The controlling mechanisms themselves required additional Infor- mation gathering and processing for adequate feedback. For example, consumer advertising was an established method of controlling the buying patterns of consumers even In the late nineteenth century. By 1910, advertising agencies widely employed information workers whose jobs were to compile statistics on the effects of advertising- feedback on the control. If you will. Later, as advertisers discovered radio, they sought Information about their audiences with the help of feedback innovations such as Archibald Crossley's telephone surveys of radio audiences (1929) and A.C. Nielsen's audlmeter, which recorded a radio listener's station preferences throughout the day (1935). (A detailed history of these spiraling developments is chronicled In The Control Revolution by James R. Beniger, published by the Harvard University Press in 1986.) 4 Introduction Information Today : The process of harnessing energy and devising ways of controlling it continues today, except that the energy most often singled out is that of the microprocessor, rather than steam or electricity. This difference is not insignificant, because in harnessing earlier powers, the effects were first applied to goods, services, and people; the informational backdrop developed slightly later. But with the application of the i, . microprocessor and related integrated circuit chips, the power under harness immediately affects the Informational part of our lives. A chip doesn't move goods or people from one town to another; it manipulates information. The result is a speedup in the quantity of information passing before our eyes and around us. FROM BATCH PROCESSING TO REAL TIME Not many years ago , it was commonplace for a small business equipped with a centralized computer system to print reports in "batches. " Every Tuesday at 3 p.m., the Computer Department would distribute print- outs of the previous week's sales activity and finished goods inventory. - That, of course, was a vast improvement over the gathering of quarterly inventory counts and seat-of-the-pants tallying of sales. But today a weekly printout is often insufficient. We virtually demand instantane- ous access to the information. Instead of batch processing, the com- puter is now responsible for tracking numerous parts of the business f. In "real time with video terminals on the desks where tons of printouts had once dropped regularly. Personal computers contribute to the increasing need for up-to-the- second information. If you are active in the stock market, for example, you can retrieve real-time stock exchange data with the computer and a modem, then perform calculations on that data vrith the help of a spreadsheet or other analysis program. Similarly, you can maintain a database of Information that is particularly useftil to you, even if the corporate computer department doesn't have time to think about your application. Personal computer software, in general, encourages the creation of "new" information, even if "new" means a different way of viewing existing data. For instance, you may have always had to prepare a quarterly budget forecast for your division or department. Without a computer, the budget was probably prepared on a columnar pad (with l:-rK many erasure marks) and then transferred to a typewritten spread- sheet. With a personal computer and spreadsheet software, you have the chance to analyze the budget from different perspectives in less time than it took to create a draft of the manual budget. You might even chart Coping with the Information Revolution. 5 the results as bars or pie wedges for the forecast meeting— perhaps to get a competitive leg up over your colleagues in nearby office cubicles. INFORMATION OVERLOAD Hie rapid increase in information throughput is not without its problems. All it takes is a casual look through virtually any business computer magazine to see that a primary concern today is passing personal computer information from machine to machine. Even within the confines of a particular computer brand and model, it Is often difficult (If not impossible, at times) to pass Information between two software programs. For example, if the maker of a particular Macintosh word processing program doesn't make a concerted effort to allow transfer of files between his program and others already on the market, you, as a purchaser of that product, won't be able to share your nicely formatted word processing files with colleagues, except in printed form. Worse yet, if you have information files stored on floppy disks and attempt to read or modify those fUes on someone else's Macintosh, that other machine must have the identical software you used to create the files in the first place. The Macintosh, with its propensity to mix text and graphics into the same document, actually complicates matters of fUe compatibility among programs and between Macintoshes and other computer maikes, such as the IBM Personal Computer and Personal System/2 families. While users of the Macintosh technology benefit irom this convergence of text and graphics modes, the complexity of storing, sharing, and distributing such Information for everyone to use demon- strates the absence of what I call an information Infrastructure. Just as transportation spread across the United States first with an Infrastructure of rail lines, then with highways, and most recently with flight paths Ikildng airports, so will computer information become prevalent around the world when an information infrastructure ts established. It will entail many computer companies reaching agree- ments on storage standards, file formats, graphics layouts, and several other technical aspects of personal computing. The technologies are perhaps too immature for such a universal standard to emerge In the near future, but steps can be taken in that direction. HyperCard is very likely one of those steps. Information Threads and Links If you've performed any kind of research, like preparing a term paper, you may have recognized that hardly any fact exists m a vacuum. For example, Julius Caesar was assassinated on March, 15th In 44 b.c. , yet 6 Introduction ' ;>T ;j o. h-,. ■ >) • it's difficult to consider that bit of information entirely on Its own. You probably have other questions relating to the incident that require additional information: who were the assassins, what was their moti- vation, on what hterature Is the actual date based, what was the political and social climate of the time, what happened after the assassination? The trouble is. If you find an Information source for the event, that fii source likely won't have the additional information you require. You need to branch away from a strictly date-based collection of facts to other collections, such as information bases centered around literature f. /; ; of the time or historical observations made many centuries later. What this points to is that information very often consists of threads emanating In many directions from a single fact. At the end of each .i-3>i i thread is a fact that itself, has additional threads running in yet other directions, and so on. You may have found yourself making such threaded connections in h:m a research project. Visualize a large bulletin board filled with Index ^ cards. Each card contains a fact or quotation exbracted from a research source. No matter how you label the cards by subject, a card may relate to more than the card positioned next to it. To help you visualize the relationships from a distance, you link two distant cards by a strand of colored yam, thumbtacked to the board. After a while, you may have many different colors crisscrossing the board. EVERYDAY LINKS Even in our personal lives , we are surrounded by interrelated facts . For example, if you buy a major appliance, the transaction has many implications on your personal Information management. You have to make sure you have the money to pay for the Item or have an amount c set aside from a monthly budget to make payments. You have to adapt *i your schedule to accommodate delivery, making sure someone will be home to meet the truck. The value of the new appliance may affect your insurance coverage. Record of the sale must also be maintained for ■n.i possible tax deductions when you next file your Income tax. And on It goes. If all this is for a relatively simple transaction, consider all the Information generated and managed by each individual in a lifetime. This phenomenon is best summed up In an excerpt from Alexander Solzhenitsyn's Cancer Ward: As every man goes through life, he fills In a number of forms for the records, each containing a number of questions . . . . There are Coping with the Information Revolution 7 thus hundreds of little threads radiating from every man, millions of threads in all. If these threads were suddenly to become visible, the whole sky would look like a spider's web.,,. RESEARCH LINKS As those webs grow, whether they contain threads of personal or business Information, it becomes increasingly difficult to locate a particular item. For example, if you are researching a topic, you might start the search in the Reader's Guide to Periodical Literature, an index to articles that have appeared in 200 popular consumer magazines. But If the subject might also be covered In technical journals, you will have to check reference works similar to the Reader's Guide that cover the subject. If you're not familiar with those reference works, you must take an additional step away from the material you seek and look into something like The New York Times Guide to Reference Materials. In other words, even the number of information cross-references is so large that we need a "guide to the guides." Each Information level we are forced to transcend in search of a fact lessens the desire to perform the search, In an inverse square propor- tion. If a related fact is two levels away, we're one-fourth as likely to make the effort to track it down; for three levels, it's one- ninth as likely. It's one thing to be thwarted In a search for "external" information, such as that found in libraries and electronic Information services, because of intervening information levels. It's quite another to experi- ence that same difficulty with the information you work with daily on the computer. Program Information Any applications program you use that saves files on the disk is an information handler. A word processing program, for example, is often the tool for turning ideas into something a bit more tangible for printing or communicating over the telephone. A spreadsheet program, on the other hand, might be more often used as a transitional information tool, transforming existing figures into presentation graphics or extrapo- lated forecasts. Even a drawing program, Uke MacPaint or MacDraw, is an information handler. Any picture you save on the disk (whether created with the program or captured by way of a video digitizer) is information. Owing to the way we've been brought up on computers and their programs, we too often consider each document as a stand-alone hunk 8 Introduction " >' V'^ : ■ ' ei of data. And unless we're working In an integrated applications environment, we probably look at a particular kind of document as having no implications beyond the current program. It's important to recognize, however, that very few saved documents exist In their private vacuums. More often, a document is only one piece of information within a larger context. A business letter, for Instance, u> i' may be one point along a communications continuum comprising a ! much larger project. Part of the letter, such as the addressee's name, address, and greeting, may be merged from a database; another part may contain an excerpt from a job-costing spreadsheet. Even among your own documents, then, invisible colored yams stretch from file to file. The Database Software Heritage , , ' One type of information management software you may already know- about is a category called database management software (DBMS). For decades, DBMS has been the cornerstone of information management on large computers. It has also been adapted for use with the personal computers that are common today. Within the personal computer category, there are two broad types of database management: file management and relational database management. FILE MANAGERS ' Mh. . . v File management software is the simplest kind of database software. The file part of its name does not refer to the kinds of files your applications generate. Rather, the file Is like a finite collection of Information, usually replicating a drawer full of ftlled-out forms. For example, one database file may consist of a collection of names, i . addresses, and telephone numbers for your business contacts. Before you can use the database, you essentially create an on-screen form to be filled out each time you add a new contact to the file. The form probably has blanks for the person's name, title, company, street address, city, state, ZIP code, and phone number, and perhaps a blank for additional notes, ■i ,v Once you have designed the empty form, you can begin entering Information. As with its paper counterpart, you fill in the blanks on a given form with information for one contact. You wouldn't type in Sarah's phone number on Tom's form, of course. In other words, all the information you deem important about that contact will be viewable on a single form. Coping with the Information Revolution 9 It is the additional duty of the file management software to offer you ways of sorting the forms so that you can "thumb through" forms In any order you see fit. Therefore, while you might keep a paper version of this file In alphabetical order by the contact's last name, the file manage- ment software allows you to sort the forms by ZIP code. The information on the forms hasn't changed, just the order in which the forms are stored. An important function of file management software is the search. If you wish to look at only those contacts in Chicago, you can Instruct the software to display only those forms whose "city" blank is filled in with the word "Chicago." From there, you should be able to have the file management program print out a report that Usts Information on the forms of all contacts you selected with the search criteria. Good file management software win give you multiple search criteria, with which you could select all contacts whose "city" blank says Chicago, and whose "notes" blank contains the word "prospect." You can then use the printed report as a way of following up on leads. RELATIONAL DATABASES A much more sophisticated type of database management is called "relational," because it extends links between individual files. For instance, if your name and address database also has a blank for a consecutive serial number for each form you filled out, a relational database will let you use that number to link the name and address database to a different database. Let's say you wish to keep a record of orders placed by companies whose names are stored in the name and address database. When designing the order form, you would set up a blank into which you wtU eventually type the serial number of the customer. You would then establish links between name and address blanks In the order form and the database that actually holds that information. As soon as you type a serial number into an order form, the relational database program looks up the name and address information from the name and address database, and displays the relevant data in the blanks. In other words, you establish threads between forms. Relational database programs also have the same kind of sorting, searching, and reporting features that file managers do. But with the ability to retrieve information from multiple databases, the Job of filling in potentially redundant blanks is greatly simplified. Both types of database management programs are valuable applica- tions for their intended Jobs. By and large, current database manage- 10 Introduction ->:Vi ViV,: v..- a;^. i ment programs for the Macintosh are text-oriented, despite their abilities to incorporate graphics elements in places. Moreover, data- « base programs generally work by themselves: there is little interactiviiy between a database and the rest of your Macintosh work. HyperCard and the Databases The above Introduction to database management software was an important prerequisite to talking about HyperCard because the two environments may appear to do the same kinds of things. In some respects that's true, but HyperCard Is not intended to replace database management software as we know it today. In fact, there will likely be many cases in which a Macintosh owner wiU use a database manage- ment program and HyperCard together. Well see exactly how that works much later in the book. Let's look at HyperCard in comparison with database management software. You can use HyperCard quite simply to perform certain operations found in file management software. For example, you use HyperCard to design Information input forms on the screen, insert information into the forms, sort the filled-out forms, and search for a particular form. But in this context, you should notice some significant differences. First, you have total control over the appearance of your forms with HyperCard. In fact, you are encouraged to design on-screen forms that resemble noncomputerized obj ects as much as possible. And by "form," we mean a much wider range than something you fill out like an application form. A HyperCard "form" can be virtually anything that you can recreate inside the area of a standard Macintosh screen: a rolodex-type file card, a calendar page, a weekly appointment book, and so on. In other words, you can use HyperCard to recreate computerized versions of real-life objects, as well as environments impossible in the physical world of paper and ink. HyperCard also has what a database management devotee would call "relational capabilities. " That's because information stored in one stack of HyperCard forms can be rehieved by forms in other stacks. Hyper- Card takes quite a large additional step, however. Unlike a relational database. HyperCard actually lets you zip over to other stacks to view the full context of related information. Thus, while a relational database generally restricts its relational capabilities to simply retrieving infor- mation from elsewhere, HyperCard lets you hop around as your information needs require. You can also use HyperCard to establish generic links between forms to speed the search for related information. nil'. Coping with the Information Revolution 1 1 For example, if a generic link exists between a monthly calendar and a daily appointment book, you can click on a day in the calendar to have HyperCard pick out the card in the appointment book file for that day. Nor are the links you establish finite or rigid. You can adjust the links as you please or create new ones as additional fUes of related informa- tion are added to your collection. The threads, in other words, can keep growing and weaving, like an ever-expanding spider web. A major distinction between HyperCard and DBMS software is In the way retrieved information is displayed and printed. A raison d'etre for DBMS programs is the ability to generate reports. A report usually consists of columnar data that lists some or all elements of a form. The reporting software then usually performs various math functions, such as providing a total count of Items in the report or creating subtotals and totals of numeric Information in the report. HyperCard, on the other hand, is not designed for generating reports of that nature {although it Is capable of simpler report printing). Instead, it Is optimized for quickly looking through existing cards- browsing— In search of desired information. Therefore, while a DBMS program might produce a report listing based on desired selection criteria (presuming you have already set up the report format) , Hyper- Card very quickly finds cards matching your criteria. The Center of Your Macintosh World * ' It should be clear by now that your Macintosh— with or without HyperCard— is a machine that thrives on Information. It lets you create fresh information, it stores old information, and it transforms one information type into another. Even the process of managing the computer's applications and fUes is an informational task. I call this Macintosh-centered concentration of personal and other Information your Macintosh World. Every application or document file, every font, every desk accessory— they are all parts of your Macintosh World. At its most basic level, HyperCard gives you the power to take control over your Macintosh World, It can be the very nucleus of your Macintosh World, From HyperCard, you will have access to every application and file; you'll be able to reach personal and business information you feel Important enough to store on a disk or file server; you'll use HyperCard to access new information bases. This last feature Is an important one. Because HjrperCard is Included with every Macintosh beginning in August 1987, its power will be available to every new Macintosh owner. Because of its mass distribu- tion, HyperCard will serve as a medium through which Apple and third- 12 Introduction vv^sk^i-X cm I: vyii\'->': t party publishers will be able to distribute information of any kind, because most Macintosh owners will have access to that information. It's true that information could be distributed in plain Text Only format, which every Macintosh word processor can load, but that medium strips away key elements, such as the relaUonships among points of information and the graphical base for which the Macintosh is well-known. HyperCard, then, will certainly serve as a critical step in establishing a long-term information infrastructure for all Macin- toshes. HyperCard will become the familiar "front end" to information access not only on our own disk drives, but in network file servers, on compact disc read-only memories (CD-ROMs), on videodiscs, and in mainframe computers linked by cable, telephone, or satellite. We won't have to worry about the storage medium or tricky commands to access remote computers: HyperCard, with the help of third-party pubUshers. ^ wUl take care of that for us. By expanding our reach for information, we extend our Macintosh World. No matter how big that world gets. HyperCard will aUow us to keep control over our Information. Programming for Poets A major barrier between potential computer users and the machines has been the lack of software taUored to narrow applications. Most commercial software tries to appeal to as broad a user spectrum as possible. Specialists, users who could truly benefit from a computer like the Macintosh, simply haven't had the tools to use a machine profitably. V. 5 Tl In the past, educators and business people dedicated to putting computers to work for them studied to become nearly professional programmers. They wrote the custom software that no publisher or commercial developer would bother with. That was difficult, but not impossible, on simple computers like the Apple II and the early IBM PC. But today, as computers like the Macintosh become easier to use, they become extremely difficult to program. It can take an experienced programmer a year or more to begin writing quaUty programs based on visual desktop environments such as the Macintosh. HyperCard signiflcantiy narrows the gap between the nonprogram- ming speclaUst and the sophisticated program he or she needs. As you'll learn in later stages of this book, HyperCard handles the hard parts of programming for the Macintosh. You'll spend more time on applying your ideas than on technical issues. Or, as BiU Atkinson says, "It's programming for 'the rest of us'." HyperCard wiU spawn a new Coping with the Information Revolution 13 cottage industry of HyperCard developers who have a clear Idea of specially needs and who now have a way to fulfill those needs for themselves and for others In the same fields. Three Points of View HyperCard may appear to be a simple program. That is mostly because of its structure, which shields new users from its more fully featured inner workings. If you've started HyperCard and have clicked on an icon or two, you have participated in only one of its three stages of complexity, the Browsing /Typing level. Its second stage, which is hardly obvious (and purposely so), is its Painting /Authoring level, which is followed closely by its third stage, the Progmnuning level. Let's use an automotive analogy to distinguish the three levels. For the majority of us, an automobile is a convenient, if not necessary, method of transportation. We buy an auto because we have a desire to get from point A to point B. Through driver training classes, we've learned how to start, stop, and maneuver the vehicle in traffic. When the fuel needle nears E, we head for a gas station to refUl the tank. And when things don't sound right or, as with tires, appear to be worn, most of us take the car into a service shop for the appropriate repairs. Our main concern, in other words, is using the vehicle as a reliable means of transportation. Our choice of model is usually dependent upon budgetary and aesthetic considerations. But many of us also see more to an automobile than Just its utility or its aesthetic appeal. Curiosity about what lies under the hood leads many of us to take a peek. After overcoming trepidations about opening the hood, we might check a fluid level or tug on a belt to make sure everything is secure. We may then progress to doing minor mainte- nance Jobs like adding a quart of oil. Suddenly we're concerned with grades of oil, trying to determine which is best for the type of engine and climate. Even at this relatively simple level of auto maintenance, we're getting our hands dirty while influencing the performance and longev- ity of the vehicle. At the far end of the scale are dedicated weekend mechanics— "hackers" of the grease pits, if you wlU. They are likely to spend more energy on improving a vehicle's performance or rebuilding carburetors than thinking about its utilitarian function. They see an automobile in terms of what makes it run rather than where it's going. Using HyperCard's Browsing /Typing level is analogous to driving the auto as a driver only. You use HjrperCard to find or enter information. You need not know anything else about the program. In fact, you may 14 Introduction 1 see HyperCard set up in browsing and typing applications thatvirtuaUy disguise the fact that they are running inside HyperCard. The applica- tions are there to help you get from point A (needing information) to point B (having information). In contrast, HyperCard's Painting/Authoring level gives you the power to peek and tinlcer "under the hood" to design simple, tiiough useful applications. HyperCard comes witii a remarkably powerful set of design tools, which you can use to modify existing appUcaUons or develop your own. , , , _r Lastiy the Programming level allows you to modify Uie performance and operation of HyperCard applications, or design entirely new applications from scratch. This level is built around an English-like Umguage called HyperTalk. While if s true that you can be a HyperCard autiior without programming in HyperTalk. I believe tiiat anyone with a desire to write an application wont be satisfied, ultimately, unless he Investigates HyperTalk's possibilities. „ _^ ^ Use Part One of this book first to learn how to drive HyperCard. Then in Part Two take a peek under the hood to perform simple maintenance and repairs. Graduate to Part Three, in which you'll don overalls and learn how to dlsmantie, rebuild, and create HyperCard apphcations with HyperTalk. Finally, in Part Four, you start working on real vehicles, applying your newfy found knowledge to real Information- handling problems. Youll then know HyperCard well enough to mold it into the master of your Macintosh World. ■ititii.m PART ONE Browsing Through H5^erCard V, . . ■. CHAPTER 1 Browsing Building i Blocks You CAN USE HyperCard strictly in rrs browsing environment and still benefit greatly from the experience. You are likely doing that already if you are availing yourself of some of the HyperCard template applications- called stacks— that come with the program. You've probably seen how easy it is to store and retrieve personal information in familiar forms, like the name and address card file or the dally appointment book. A well-designed stack makes information storage and retrieval painless, if not fun and Inviting. User Preferences Veiy much aware that HyperCard's advanced features may overpower newcomers, the program's design team established five levels of complexity. As you grow comfortable with each level, you can graduate to the next, with HyperCard revealing more menus, commands, and internal facilities that you'll need for each level. The user level is set in a special card in the Home Stack called User Preferences, shown in Figure 1 -1 . From the Home card you have many ways to get there. The sure-fire way is to choose Home and Last from the Go menu or to type Command-H and Cormnand-4 (the Command key Is the one with the symbol— press this key and the H or 4 k^ simultaneously) . 17 18 Browsing Through HyperCard User Preferences User Name: Danny Goodman User Leuel: O Broiusing t » ® Typing O Painting O Authoring O Scripting V Figure 1-1. The User Preferences card in the Home Stack set to Typing level 7^H3i.i--- ' Each level adds powers to the abilities of the previous level. Hie five OK ( levels and their respective powers are as follows: •: Level Powers and Abilities Browsing Find information only; no text entry pr editing. Typing Adds text entry and editing on cards. Painting Adds access to the Painting Tools. Authoring Adds access to Button and Field Tools. Scripting Adds access to HypeiTalk scripts. To continue with this book, be sure your user level is set at least to the Typing level (there's little need for the Browsing-only level unless a HyperCard author doesn't want you to change text in his stack). At the Tr' V,'.: Typing level, the menus are kept to a minimum for newcomers. If you \, V, select a higher user level now, some of the menu illustrations In these first three chapters may be different than on your Macintosh. That's OK ^ with us, as long as you are aware of the potential differences. We believe that the Browsing and Typing levels are so intertwined that for the balance of Part One, we will refer to the Typing level as the browsing environment In most HjrperCard applications,'like the Ad- - , dress and Datebook stacks supplied by Apple, browsing and typing really go hand in hand. When you use HyperCard for simple information storage and re- trieval, you are approaching the program with a browser's point of view. Browsing Building Blocks 19 You need know very little about the inner workings of HyperCard to use a well-designed stack productively. Still, you can significantly enhance your experience as a HyperCard browser with an appreciation for a few fine points of a stack's basic structure and how you interact with it. Our immediate goal in these first chapters is to help you browse— find and store Information— efRclently. The concepts will also be essential for further exploration about HyperCard's authoring powers later. nie only assumptions we make about your HjrperCard expertise is that you have looked through the HyperCard manual and have completed the tutorial. We won't be showing you how to use the stacks provided with HyperCard (the manual and tutorial do that nicely), but we will use those stacks frequently to demonstrate features and concepts. In many places throughout this book, you'll be given the opportunity to type and mouse along to step-by-step instructions. Following along will help you master HyperCard much more quickly— we strongly suggest It. The Basic Elements Working through HyperCard's browsing environment wiU be much easier once you acquaint yourself with its nine major elements: ° Stacks • Backgrounds , .h-yA-yat imrtt lo ^.tcs vd .osta s nyqo itoY Cards A'ju-: •>i';'?'ob vum i;ov .bvai ° Fields " Buttons ' The Home Stack ,m " Recent ' The Help Stack " The Message Box The first five items are the basic building blocks of any HyperCard application; the next three are navigation aids that are always available to help you out of a jam; and the last element is an important communication medium between you and HyperCard. Once you know what these elements are, you should have a firmer understanding of what you see on the screen while browsing. As HyperCard's name and many items in the above list imply, the program is largely a metaphor for collections of information stored on cards, much like a card catalog at a library. We'll use the card catalog model to describe the functions of the major HjrperCard elements. 20 Bramsfng TTirough HyperCard Stacks We can Uken a HyperCard stacK ^"^"^ „ example, if a car d weHn.itthecor.tentsof— ~ drawer were labeled Trees, yo"^«"i5^ HvDerCard version of that of references to arboreal subjects T^il!!^. drawer would be a stack, also labeled i^ees^ Hiskfile which you Each stackln HyperCard is a ^-^^^'^"^^^^l^^^^to^^^ can see as a HyperCard document ^^^^^^^^^^^^ you of — rtirr.re=s^^^^^^ 'lus. wher. you insert tl^^»^-^-2«^^^ Macintosh disk drive and open me folder 1^^^^^^^ ^^^^ .^^^ comparable card catalog drawer^ of the disk device you use to store it. ^^^^^ level, you may double-click on the desired stack icoi^ autorZaUcally starts Hyp^rCar^^^^^^^ second, J" ^^^^^^[P^s^ri^^^ what is called a standardjzte the ^i^^J"^fJ;^f . Wh^ you access the stack name as you dialog box [Figure 1--5) f/^^^^oeram. Select the stack name HyperCard HyperCard Stack FiQure 1-2. HyperCard appUcamn and document icons Browsing Building Blocks 21 — HyperCard Starks Fn= 1 2 items 1 7 J7ZK in disk t ,247K available Area Codes Address Datebook File Index B^^^lf o Home Phone Quotatiorvs HyperCalc Periodic Table Plots Slide Show 0 o F^we 1-3. Stack icons in a folder File Neiu Stack... | Open Stack... mO Sane a Copy... Page Setup... Print Card Print Stack... Print Report... Quit HyperCard Pfgure 1-4. HyperCard File menu with Open Stack... selected 22 Browsing Through HyperCard Q HyperCard Stacks □ Hddress □ Rrea Codes □ Book Shelf D Datebook □ File Indett □ Home □ HyperCalc D Periodic Table D Phone HD-20 [ Or! Open ] Cancel ] Figure 1-5. Macintosh standard file dialog box for opening documents HyperCard must be able to find a stack that you open by clicking a button. HyperCard might not find a stack if the stack file is nested in a folder or located on a disk other than the one(s) to which it has ready access. If HyperCard cannot immediately find a desired stack. It displays the standard file dialog box for you to show HyperCard where the stack Is. In the case of stacks nested in folders, you can Instruct HyperCard to automatically search through specific folders (by folder name) for stacks and other kinds of files. We'U describe how to do this tn detail in the section on the Home Stack in this chapter. You don't really close a stack, per se. By opening one stack, you essentially close the previous stack. When you're through with your HyperCard session, choose Quit HyperCard from the File menu. This action closes the current stack and brings you back to the Desktop. ABOUT SAVING STACKS ' ' As you'll learn in more detail later, information entered into a Hyper- Card stack is automatically saved to the stack file for you. But you can store a cof)y of the current stack on disk by choosing Save a Copy. . . from the FUe menu . You'll be prompted in a standard file dialog box for a file name, although HyperCard suggests the current stack name preceded by the words " Copy of", as shown in Figure 1 -6. This is a good way to make a copy of a stack on a floppy disk to ^ve to a friend or colleague. Browsing Building Blocks 23 ^ HyperCard Stacks | D ?lr« = S ( HD-20 — ^ D lUiiiiiHHik 1 D fiUy imii^n | D Home J[ > Saue a copy of stack in: ( Saue Copy of Home 1 [ Cancel Figitre i -6. Macintosh sfandord^Ie dteiiog box for saving documents. The only saving needed in HyperCard Is savir\g copies of existing stacks. Backgrounds Let's say you pull out a Ubraiy catalog drawer labeled Trees." If this drawer were in a regular library, you'd expect to see it loaded with cards , perhaps of the index card variety, with horizontal lines printed on them . In other words, before any Information was entered onto any card, the card had a background of horizontal lines preprinted on it. Those lines will be on every card in the drawer, regardless of the other information entered onto a card. Let's also say that some cards in this "TYees" drawer contain miniature pictures of various tree species. You wouldn't want to draw the pictures on cards filled with preprinted lines. Instead, you'd want a blank card or one with a rectangular area on one half of the card, set aside for the picture, and horizontal Unes on the other half, for a written description. In other words, you'd want two preprinted backgrounds, or formats, available in this drawer to accommodate two different kinds of information {Figure 1-7). A HyperCard stack accommodates this need quite readily. You can design a HyperCard stack to have as many different backgrounds as the information in the stack requires. More often than not, a HyperCard stack will have only one back- ground. The Address stack provided with HyperCard Is a case in point. Its background consists of a rolodex like card surrounded by a grey fill pattern. A few other graphic elements, like the arrows and telephone 24 Browsing Through HyperCard Figure 1-7. Two different backgrounds may be needed for the same information 'drawer." e.i'' nii, icon, are also present on this background [Figure 1-8). They appear on every card in this stack, as if the cards came preprinted. At the user levels of Painting, Authoring, and Scripting, you can always filter out foreground elements to see what a card's background is at any time. Simply choose Background from HyperCard's Edit menu (or type Command-B). HyperCard temporarily hides everything in the foreground (hides, not erases). To restore the foreground, choose Background once again. Some stacks may appear to have no background: When you choose Background, the background turns all white. This is perfectly natural for some stacks, whose Ccirds contain a fuU screen of graphic informa- tion. Even though the background appears empty, that empty space is, nonetheless, considered a HyperCard background. Eh}ery HyperCard stack has at least one background, even If it is blank. "ri'T Cards When you puU open a card catalog drawer, you usually see many cards— 3" x 5" cards in most libraries. Typically, a single card contains Browsing Building Blocks 25 Figure 1 -8. The Address stack has one background, which includes the greyjili pattern, the representation of a card, and other graphic elerrwnts. one piece of information related to the content of the entire drawer. The content of one card is different from that of any other card in the drawer. Such is the case with a card in a HyperCard stack, A card is added to the stack each time a new piece of information is added to the collection, as when a newly fllled-out form is to be filed away, A card may contain text information, graphics information, or both, A card in the Address stack, for Instance, contains strictly textual data, like names, addresses, and phone numbers (remember: the card picture, arrows, and icons are in the card background). In contrast, the stack called "Art Ideas" on HyperCard's Ideas disk contains text and graphics information on each card; This information changes from card to card in the stack (Figure 1-9). The white, drop-shadow "card" area, its surrounding grey fill pattern, and icons are in the background, A card is not restricted to carrying only one piece of Information. You'll see applications in which a stack is actually a long list of words (as in a dictionary). But to keep the size of the stack file on the disk to a minimum, each card contains as many consecutive words in the list as wfU fit while remaining readable (Figure 1-10), . 26 Browsing Through HyperCard Books, Articles, Newspapers INSIDE WRITE 4m C3 1^ Figure 1 -9. An Art Ideas stack card has text data tn the upper left corrwr and graphics data below the heavy line. The picture of the white card, greyJUl pattern, and icons at the upper right are in the background. .dt. si it - ill # rile Edit Go Tools Objects DIMINUER dimlnuer (v) -- to reduce dinde Cr) -- turkey diner (v) ~ to have dinner dtner (m) -- dinner dIocBce Cm) -- diocese dlphterie (f) — diphtheria dIplomotB (m) ~ diplomat diplSme (m) — diploma dire (m) -- speech, words direct Cadj) -- straight, direct dirigeoble (m) — airship dirigeant (m) ~ leader diriger (v) -- to direct, manage disciple (m) ~ follower DISGRACE discipline (f) -- discipline discordant (adj.) — dissonant discourlr (w) ~ to discourse discours (m) ~ speech discourtois (adj) ~ rude discredit (m) -- disrepute discret (adj) ~ discreet disculper (v) -- to exonerate discussion (f) ~ discussion discuter (v) — to discuss disert (adj) — eloquent disette (r) -- scarcity diseur (m> ~ speaker disgrace Cf) ~ disgrace Figure 1-10. Stacks consisting of lists often contain many pieces of information on a single card, like this French dictionary. • Browsing Building Blocks 27 Fields ™" — ' - ' Cards in the library card catalog are loaded with textual information, the "stuff" for which you are looking. This Is the information that usually changes from card to card. For example, every card in a stack may be imprinted with the name of the library system (for example, SmallviUe Public Library) in the background. While that bit of informa- tion is helpful, it is not the information for which you are likely to browse through the stack. The important information on the card is the content, such as a book title, its call number, and so on. Textual Information that changes from card to card In a HyperCard stack almost always exists in fields. Fields shouldn't be anything new to you. If you've used your Macintosh to save a new document in virtually any application, you've used a text field without realizing it. When you choose Save As. . . from a program's File menu, you usually see a dialog box like the one in Figure 1^. The rectangular area at the lower left comer of the box is a text field, into which you are to type the name you wish to assign to the document. Fields in a HjrperCard card may be only a few characters wide or many lines deep, depending on the nature of the infonnation carried on the card. The size of a text field is established by the person who originally designs the card In the stack. We'll have more to say about the dynamics of fields in chapter 2 when we discuss entering information Into a card. Of the nine basic elements of HyperCard listed earlier, buttons have no direct analog in the world of card catalogs, at least not in the real world. So let's imagine that we're reading a card in a drawer labeled Trees." Amid the textual information on the card is a reference to an Important botanist of the early twentieth century. If you get the urge to learn more about this person, you would normally have to go to smother drawer containing biographies, and flip through the cards until you find the desired card. But what if the original card had a magic button you could press that instantaneously pulled out the biography drawer and flipped to the botanist's card? That's the kind of action a HyperCard button can perform. On a HyperCard card, a button can have one of many forms. Sometimes they'll look like the buttons you commonly see in dialog boxes (Figure 1-11). At other times, a button will look like an icon whose picture indicates the kind of action that results from a press of the button. Still other kinds of buttons will be situated atop text fields or 28 Browsing Through HyperCard [Round Rect Style) ^ Check Boh Style ® Radio Button Style Figure 1-11. HyperCard stacks often have these ftuniliar-looking button styles. '"' ' ' may be entirely Invisible, depending on the aim of the application author. No matter what the design, however, a button is activated by simply using the mouse to move the pointer atop the button and pressing the mouse button once. In HyperCard, there is no need to double-click on a button. One click, and the button's action begins. Notice that we've been using the word "action" when referring to the result of clicking on a button. We can't emphasize this enough: Clicking on a HjrperCard button In a predesigned HyperCard stack wUl cause something to happen. You may zip to a different stack, hear a musical tune, or go to another card, A well-designed stack should let you browse through Its information (or find related Information) simply by clicking buttons. Buttons, therefore, are your primary navigational tools as you browse through a HyperCard stack. In more powerful roles, they wUl help you locate related information in the same or different stacks, helping you thread your way through a vast quantity of stored information. The Home Stack The old saying There's no place like home" holds ever true In Hyper- ' ' Card, "Home," however, is actually a stack that has special properties ■ ^ of particular interest to those who pursue HyperCard authoring. For browsers, however, the Home stack is best described as a kind of master mdex to all the stacks your Macintosh can access. As you get more comfortable with HyperCard, the physical makeup of your Home stack may change from what HyperCard initially comes with. But it Is a good idea to stick with the original setup for a while, until you gain confidence as a HjrperCard author. Unless you have changed the HjrperCard program. It vrill display the first card In the Home stack whenever you start HyperCard from the Finder. The first card in this stack which Is called the Home Card, usually displays icons representing each stack to which you desire Browsing BuUdtng Blocks 29 quick access. You could think of the Home card as a small replica of the drawer fronts of an entire library card catalog cabinet. Clicking on a drawer's icon pulls open the drawer, giving you access to its cards and information. A stack need not have an icon on the Home card for you to open that stack. You can always choose Open Stack from the File menu, and select the desired stack file from the standard file dialog box. In HyperCard terms, the Home card normally contains many but- tons. A click of a particular button sets in motion the necessary actions to open and display the stack that is "linked" to that button. Later well show you how to transfer a button and its icon from a stack to a Home card to speed the opening of that stack (that is, obviating the File menu operation). Incidentally, the actions associated with buttons on a Home card can range from simple to more powerful than you might Imagine. On the simple side, for instance, a Home card button can open a stack and display the first card of the stack. A more powerful button might open the stack and search for the card that contains today's date tn one of its text fields (the Datebook stack on your HyperCard disk does this, for example). FILE PREFERENCES Hie Home Stack also contains three special cards that help HyperCard find stacks and other fields that may be nested in disk folders. The cards are labeled: Look for Stack in: ;r.i nuiin'ton Look for Applications In: Look for Documents in: These cards, like the Stacks card in Figure 1-12, list pathnames, which guide HyperCard in its search through your disk(s) for stacks. Because the concept of pathnames maybe new to you, an explanation is in order. When you wish to open a Macintosh application or document fi-om the Finder, you go through a subtle search procedure to find the icon so that you can double click it. By opening a disk Icon, you can see the topmost level of fUes and folders stored on that disk. This level Is called the root (or root directory], because all disk organization starts from this level. As you open folders to see the desired document Icon, you are essentially cutting a pathway from the root to the icon. Behind the scenes the Macintosh, meanwhile, traces your steps down the path, building a list of folders through which you reach your iconic destina- 30 Browsing Through HyperCard Look for Stacks in: .;Byp.erQard.Stack3:., .;.My...S.ta,ck,s;„ iH,e.lp...S.t.3.c.l<;§;.. :J..de.a,,Stacks;. .:dy,.Stack5:WQrk,StLjff; .;dy.itack.3:..Woti.Stuff:.Sj3e .:D.S3„StackaL , Figure 1-12. The Stacks card in the Home Stack establishes folder pathnames HyperCard should search through to locate and open stacks. tion. Hiat list, including the Icon's file name, is called the pathname of the file. PATHNAME NOTATION The notation for a pathname places colons between folder and file names. Therefore, a pathname HD-20:Applications:Word Processlng:MacWrite Indicates that the disk (also called a volume) name is HD-20, which contains a folder called Applications; this folder, In turn, contains a folder called Word Processing; the Word Processing folder contains the application file MacWrlte. This pathname and folder organization is illustrated In Figure 1-13. A notational shortcut lets you omit the disk (volume) name by beginning a pathname with a colon. The Macintosh assumes you mean the current volume. If you use only one hard disk all the time, this method works fine. Back to the Stacks card In HyperCard: You can list the pathnames '■^ " HyperCard should use to search for a stack. If all your stacks are stored In a folder called HyperCard Stacks, then that's the only pathname you'll need to list. As your collection of stackware grows, however, you'll start building other folders and pathnames to organize them. Browsing Buildtng Blocks 31 h»-2a HD-20: Vord Prpcessinj Appllutions HD- 2 OiAp plications; H D- 20 lAppl i cati o n3:Word P rocessi ng: = HD-2D:Applic8tion3:Word Processing: Mac Write MaoVrit* Figure 1-13. Pathnames reveal names of the disk volume and folders opened on the iDoy to the desired Jlle. If you aren't sure about a pathname, you can use the Find File desk accessory to get the details. Use the accessory to search for the stack name. Then click on the file name. Its folder pathway wfU be spelled out in the lower right comer (Figure 1-14). Build the pathname Jrom the bottom to the top. You can omit the disk name, but In that case be sure to start the pathname with a colon. Find File CD HD-20 Search for: 1.0 'i* Pi?sEiJit 1 X) ResEdit Created: Thu, Sep 4, 1986; 7:00 PM Modtfied : Thu, Sep 25, 1 986; H :1 4 PM Siie: 1 57875 byte J ; 154.5K on disk ^ Utilities Q Pascal ^ Programming EZJ HD-20 1^ Figure 1-14. Use the Find FUe desk accessory to determine a stack's Jidl pathname (lower right comer). Then assemble the name from the bottom up. 32 Browsing Through HyperCard The Applications and Documents pathname cards perform the same function as the Stacks card, but HyperCard looks to these lists when a button asks it to start an external application and document. If a stack features a button that opens other programs and documents, these files' pathnames must be listed in these two Home Stack cards to assure a smooth transition to the program (that is, without asking you to find the files with the standard file dialog box). When HyperCard cannot locate a stack, document, or application, a file dialog box appears with the prompt "Where Is" followed by the sought after filename. After you manually select the file. HyperCard logs the pathname In the appropriate listing. Thus, you may never have to consult these pathname cards, Recent HyperCard does its best to stay In the background while you search for Information. The program tries to be subservient to a variety of searching methodologies, described later. Recent offers you a way to quickly find a card you saw "recently, " vrithout forcing you to figure out which stack that card may have been in and how to navigate to it. In the library card catalog model, Recent would be like tagging the last forty-two different cards you browsed through, even if they were in Figure 1-15. Recent shows miniahjres of the Inst forty-two cards for instant access back in time. Browsing Building Blocks 33 many different drawers. When you needed to look at a recent card, you could find the tag and Immediately go to the card. As you step through cards in a stack or jump from one stack to another, HyperCard maintains a kind of photo album of your moves. Miniature representations of the last forty- two unique cards you viewed on the screen are stored In Recent (Figure 1-15). Only one representa- tion of a card appears, no matter how often you go that card. To look at any one of those cards, simply choose Recent in the Go menu, or type the keyboard shortcut, Command-R. Then click on the screen you wish to see. You can also step back In time without going to the Recent screen. Whenever you are browsing through cards (that Is, navigating by way of the mouse), you can choose Back from the Go menu or press the keyboard key sdesignated as the Go Back keys. On the Macintosh 5 12E and Macintosh Plus keyboards, it's the tilde (~) key, located at the upper left comer of the keyboard (Figure l-16a). On keyboards designed for the Macintosh SE and Macintosh 11, you may use either the tilde key (located immediately to the left of the spacebar) or the Escape key p| ( 2 5 4 b 6 ? B 9 1) ■■ q w e r 1 y n \ «) p 1 I ■ ■<% (1 t 9 h J k \ 7 t 1 n rr h Figure 1-16. Command and tilde key locations on the Macintosh keyboards: (a) Macintosh 512E and Macintosh Plus: (b) the "Apple Keyboard' for the Macintosh SE and Macintosh II.) 34 Browsing Through HyperCard - (Figure 1 -16b). On any keyboard with arrow keys, you may also press the down key to go back one screen (£tnd the up arrow key to go "forth") . • . Issue the command again, and you'll take a second step back. Note that going back (and forth) retraces your precise steps, including 1, . repeated vists to the same card. Going back, therefore, differs from Recent. . , Back and Command - ~ come in very handy when you accidentally . ! click on a button or just want a quick referral to a recent card. Think , . , of It as a multiple step Undo command. The Message Box ' ' < • t ' - ^ The last item in our list of essential HyperCard elements is the Message ••sxiii- Box. It has many functions, but we can characterize its underlying \: ■ purpose as being the primary communications avenue between you and HyperCard or between you and a HyperCard stack. ■ If the Message Box is not showing on your screen, you can make it appear by typing Command-M or choosing Message from the Go menu. Similarly, you can hide the Message Box any time by pressing Com- I mand-M again or choosing Message from the Go menu. The Message : Box also has a small close bcucin the upper left comer. Clicking here also ; ■; hides the box. ' ~ The Message Box is a special kind of window (Figure 1-17) designed for HyperCard (although windows in its style, informally called a f wind old, may eventually appear in other Macintosh programs). Where ,i„ you would expect to find a window's title bar, the Message Box has a i ■ thin grey bar. This design makes the Message Box a bit smaller than a ' ^ ^ standard window design. It won't hide as much of a HyperCard stack screen as a standard window would. But as with most Macintosh na. ■ ■■ -' " ■ --i This is the Message Box Figure 1-17. The HyperCard Message Box mmB&^msmmmm ■ — ■ This I Figure 1-18. When you type into the Message Box, the Jlashing text insertion pointer shows where the next typed character will go. Browsing Building Blocks 35 windows with title bars, you can drag the Message Box around the screen by placing the mouse pointer anywhere on the top bar (except in the close box), holding down the mouse button, and rolling the mouse around your desk. When the box is in its desired location, release the mouse button. You are free to move the Message Box as often as you like, anywhere on the screen . HyperCard won't let you accidentally drag the box entirely off the screen, out of reach. Another special property of the Message Box is that it has a single line for text display. When you wish to type into the Message Box, you should be aware of the condition of the flashing text Insertion pointer (Figure 1-18). If there is no flashing text pointer in the Message Box or elsewhere in the card, then the next characters you type go into the Message Box, automatically erasing whatever text was there previ- ously. This erasure is not as frightening as it may sound; in fact, it turns out to be rather helpful, as you'll see shortly. At the entry of your first cheiracter, the text pointer appears. That means that you can edit the Message Box text line, just as you would any piece of Macintosh text, including backspacing, cutting, copying, and pasting. The text pointer disappears after one of the three following actions: 1) pressing the mouse button with the cursor in any text field outside the Message Box; 2) pressing the Return key; and 3) pressing the Enter key. Pressing either of the two keys tells HyperCard to perform specific tasks with the text in the Message Box (detailed next) . With the flashing text pointer gone, you can start typing into the Message Box again. If you wish to clear the Message Box of its contents, press the Clear key, which is located on the numeric keypad section of Macintosh Plus, Macintosh SE, and Macintosh II keyboards. You needn't dwell on the detailed actions and reactions to typing in the Message Box. You'll learn its operation quickly enough by forgetting the rules and observing its response to situations in which you will find yourself often. Now let's look at the kinds of "messages" that appear in the Message Box. SAMPLE MESSAGES '''' '''^^ ' ' First of all, you can type commands into the Message Box. Commands are actually words in the HyperTalk language vocabulary. You certainly don't need to be an experienced HyperTalk user to issue useful commands in the Message Box, For example, one of the simplest commands is the go command. Go is the most-often-used HyperTalk command, because it helps you navigate through HyperCard or a HyperCard stack. We'll demonstrate 36 Browsing Through HyperCard a simple go command to navigate from stack to stack. Follow along on ■ your Macintosh. yi^^r'^rirf, .•<: vc,r?:s,r<,; • :f:n;,-->^ 'l^ 1. start HyperCard, ' ' : j> « ^ The Home card should appear. If the Message Box Is not , , ; showing, type Command-M. 2. Type go to Address into the Message Box. If other text is already In the Message Box, it wiU be replaced by . . ] this command. This command tells HyperCard to open up the ' r stack named Address, which is probably already familiar to ■ • ■ ■' ' ■ ' 'M . Incidentally, here are two useful shortcuts. First, the "to" is ' r ; . : , . optional after the go command. You can also type 50 Address to achieve the same effect. Also, HyperCard is not finicky about . , capitalization. You can tj^je in all lower case, all upper case, or j.,, !/ / • any mixture you Wish. .a - ? - nt ■ ; . 3. Press the Return or the Enter key. j - -/; t r . ; , _ ^ HyperCard brings you instantly to the first card of the Address ' " stack. Note that you may use either the Return key or Enter key , , ^' to send the command to Hj^jerCard. > ,1 While it's true that you would probably go from the Home card to the Address stack by clicking on the Address stack's icon, you might use the go address command when you are in a different stack. Instead of i; finding your way back to Home to click on the Address stack icon, you could type go Address into the Message Box. HyperCard would bypass all Intermediate steps and bring you to the Address stack instantly. , i i. As a final demonstration of Message Box commands in this chapter. V, ; we'll show you the one command that always gets you out of a navigational jam: the go home command. 1- From any stack, type go home into the Message Box. You can also type go to home. ' 2. Press the Return or Enter key. , - vv-: . , i >i : ' instantly return to the first card of the Home stack. The go home command is the same as choosing Home from the Go . menu. i • . ' You also type into the Message Box when you want HyperCard to search a stack for textual information. We'll examine this in great detail . in the next chapter. Browsing Building Blocks 37 (a) 2*32/100 + (b) 0.64 Figure 1-19. The Message Box can be used as a quick calculator. Enter a problem and press Return or Enter. THE MESSAGE BOX AS CALCULATOR • The Message Box also functions as the digital display of an electronic calculator. This built-in feature of HyperCard can be used with any HyperCard stack. To use the calculator, simply type in the problem you want to solve, as shown In Figure l-19a). Then press the Return or Enter key. HyperCard Instantly produces the result in the Message Box (Figure 1- 19b). Do not type an equal sign (=) at the end of the formula; just press Return or Enter. The Message Box breaks its rule about automatically replacing its contents at the press of the next key when that next key is one of the four basic arithmetic operations. After the HjrperCard calculator pres- ents the result of a calculation, you can type +,-,*, or / to perform an additional calculation on the result. Try it now. 1. Type the formula 25 • 40 into the Message Box CFigure 1-20). Spaces between numbers and operator signs are optional, so 25 * 40 Figure 1-20. Spaces between numbers and operators are optioned. Browsing Through HyperCard 2. Press the Return or Enter key, . . The result, 1000, appears tn the Message Box. 3. Type a plus sign {+). . i -.x- , ;n - HyperCard saves the previous result and displays a plus sign. with a space on each side of it. 4. Type 500 and press Return or Enter. The result, 1500, now appears In the Message Box. You can go on chaining calculations like this all you want. Just remember, however, that pressing any character other than the four basic operators will erase your previous result from the Message Box. The HyperCard calculator behaves Just like an algebraic scientific calculator, not like a Hewlett-Packard Reverse Polish Notation (RPN) type. This means that you can add parentheses around expressions to make sure the proper operations are performed as you expect. For example, if you wish to add two numbers and multiply their sum by a third number, you would enter the formula as shown in Figure 1 - 21a. If you don't put the parentheses in, HyperCard calculates the multiplication first, and then the addition, giving you a different result (Figure 1-2 lb). HjrperCard's calculator adheres to a standard hierarchy of algebraic calculations. In other words, when facing a string of calculations, the calculator will solve operations in the following order: Figure 1-21. Message Box math is algebraic in nature. Parentheses play a vital role in some calculations. Browsing Building Blocks 39 functions multiplication/division addition/ subtraction Only by placing parentheses around operations In lower levels of the hierarchy (for example, addition and subtraction) will you be assured the desired result. The calculator comes equipped with a couple of "preprogrammed" functions and constants to give you more than simple arithmetic. Although HyperCard calculates with greater than 16-digit precision (that is, 16 places to the right of the decimal). Message Box results are displayed to six decimal places. Type the following problems into the Message Box and press Return after each one to see the results: 3'^2 (three to the second power; three squared) (three cubed) pi (pi) pi * 12^2 (pi times twelve squared) sin (45) (sine of 45 radians) cos (75) (cosine of 75 radians) With the basic HyperCard building blocks under our belts, we can now move on to techniques for finding existing information and entering new. CHAPTER 2 Finding and Entering Information The bulk of the tasks you'll perform as a HyperCard browser will involve flndlng and entering Information. In this chapter, you'll learn about vitally important text search techniques, how to enter and edit text Information in cards, and how to create and delete cards tn an existing stack. Finding Information in the Real World - ,".,4r < Few things are more frustrating for a computer user than needing a piece of information stored on a disk— someplace. Locating that information usually requires exiting the program you're In, starting another program, opening the information file, and then performing the search. By the time you find what you're looking for, you've forgotten why you needed the information in the first place. Consider what this scenario would be like in a noncomputer environ- ment. Let's say you're drafting a report on a pad of lined paper when you realize you need to include some numbers from a budget you wrote out on a columnEir pad the previous day. Following the computer example above, you'd have to put the report pad away in a drawer, pull out the budget sheets, and then look for the figures. Putting those figures into your report would require Jotting down the numbers on a scratchpad, putting away the budget sheets, and then retrieving the report pad from 41 42 Browsing Through HyperCard the drawer. Of course, no one would do that in a noncomputer environment. So why should we have to do it with a computer? Retrieval Environments HyperCard solves that problem for the majority of information retrieval needs on your Macintosh, particularly those Involving information stored in a HyperCard application. It actually solves the problem in two ways, depending on which is more accommodating to the way you use your Macintosh. You can use HyperCard as a stand-alone application or In a multiple-applicaUon environment, like Switcher or programs of its type. STAND-ALONE HYPERCARD Running HyperCard as a stand-alone application means starting the program from the Finder. In other words, HyperCard becomes the main program in your Macintosh. For many people, this will be a quite appropriate way to use the program. You have full access to every nook and cranny of the program, both the browsing and authoring struc- tures. Before you think this too restrictive because it separates you from your applicaUons, HyperCard has a feature that lets you open external programs and documents. In essence, you will have access to any application program and any document created by your applicaUons directly from HyperCard, The importance of this is that you can use HyperCard as the center of your Macintosh World in a way that the Finder is not empowered to do. HYPERCARD WITH MULTIFINDER • ^ . • :r,f l - v : < Because HyperCard will likely become the major repository of your day- to-day information, as well as a highway to archival information stored elsewhere (on a file server, an optical mass storage device, or an on-line database, for example), you wUl want ready access to it while you are using applications. For example, if you are writing a letter and need the full address of the recipient, you'll want quick access to your HyperCard ■ name and address card file without quitting your word processing program. In a computerless world, you would simply lay your address book " ^ ' atop your writing pad, look up the address, copy it to the pad, close the address book, and continue writing. Interruption is kept to a minimum. Finding and Entering Information 43 You can use HyperCard in almost the exact same way if your Macintosh has more than one megabyte. When you install HyperCard in MultlFinder, you can summon Its browsing powers any time you are in another application program. MultiFinder keeps more than one application open at once, although only one program is usually active at a time. Therefore, in the address example, you might be typing the top of the letter in your word processing program and come to the spot where you need to type in the address. Switch to HyperCard. Then use HyperCard's searching abili- ties (described below) to locate the name and address card of your addressee. Use the standard Macintosh editing techniques to select the address lines and copy them into the Clipboard. Next switch back to your word processing document, where the text pointer is in the exact spot you left it before switching to HyperCard. Because the address is still in the Clipboard, you can simply choose Paste from the Edit menu (tn most word processors) to insert the address. It takes longer to explain it in words than to actually do it with your Macintosh. The significance of having HyperCard available as a second applica- tion in MultiFinder is that it Is far less disrupting to your train of thought to branch to HjrperCard for information the instant you need it. In fact, you will see more and more Macintosh software products provide HyperCard stacks for their on-line documentation to be used in MultiFinder or similar environments, such as Andy Hertzfeld's (Note: HyperCard requires an application memory size of nearly 750K. With the amount of memory reserved for the System File, this doesn't leave enough room to use HyperCard with another program in one megabyte of MultiFinder memory. If you upgrade your Macintosh to more than one megabyte of memory, you'll be able to assemble a highly Integrated software setup along with HyperCard.) Using the Browse Tool WTien we described buttons earlier, we said that you need to click the mouse pointer on a screen button to set that button's actions In motion. To respond to the click, however, a button requires that the mouse pointer be in the form of the Browse tool (Figure 2-1). In fact, when you are in search of HyperCard information, you will always want to have the Browse tool showing. 44 Browsing Through HyperCard Figure 2-1 . The Browse tool, in normal size (heJQ and magni^d (right) In the Browsing and Typing "ser levels, you will never find yourself out of the Browse tool. At higher user levels, however, you may need to get back to the Browse tool from any of the other tools available at those levels. While most HyperCard stacks automatically hand you the Browse tool when you need it to click on a button, you should know how to reach for it, in case a different tool is showing. Pull down the Tools menu (Figure 2-2) . You will see a palette of eighteen tools. The only one we're concerned with right now is the one at the upper left comer, the one that looks like a hand with its index finger extended. This Is the Browse tool. If this tool in the palette Is highlighted, as in Figure 2-2, you already have the Browse tool available. If another tool is highlighted, simply use the mouse to click the Browse tool. When the Tools menu disappears, the mouse pointer on the screen will become the Browse tool. Tools o r — T 1 1 1 1 i 1 O A O Figure 2-2. The Tools palette. Selected in the upper left comer is the Browse tool. FtmUng and Entering Infonnation 45 Flipping Through Cards ' ' " ' " One way to find information once you are looking at a HyperCard stack is to flip through cards one by one, Just as you might in a card catalog drawer. This may seem to be inefficient in light of HyperCard's advanced search capabilities, which we'll see in more detail in Just a moment. But as you know if you've ever done research involving leafing through a series of cards or references, it is often beneficial to look at information that may be sorted in the same category. Therefore, HyperCard gives you ways of looking one card ahead or behind the card you're looking at, ■ ^.^ , ^ , , . ARROW KEYS If you have a Macintosh keyboard with arrow keys, the task is quite simple. The left- and right-facing arrow keys bring up the previous and next cards, respectively (Figure 2-3). HjrperCard also gives you key- board access to the previous and next cards, in case you're using a Macintosh keyboard lacking arrow keys. Press Command- 2 and Command-3 to go to the previous and next cards, respectively. These keyboard commands perform the same actions as Prev and Next In the Go menu. That menu also contains selections for the first and last cards In the stack. (a) ■ f 2 3 4 5 6 1 B 9 0 ■ - 1 q m B r i \ n i & p I I •■-■ create the third card, the first card you created stays at the iront of the s ; i stack. The order can change, however, with the help of the sorting powers of HjrperCard. For example, if you create three cards in your name and address stack in the order of Tom, Dick, and Harry, these three cards are the first, second, and third cards in the stack, respectively. Tom is at the front of the stack. When you sort the cards to put them into alphabetical order, however, they will come out In the order of Dick, Harry, and Tom. Dick is now at the iront of the stack. If you keep pressing the right arrow key on the keyboard, you will keep cycling through the cards in the order of Dick, Harry, Tom, Dick, Harry, Tom, and so on. (Internally, HjrperCard assigns two numbers to each card: the current number of the card relative to the front of the stack, and a permanent serial number, called Its "card id." While the relative card number can change as the result of a sort, as we just saw. the permanent id number never changes and wUl never be reissued to another card in that stack, even if the original card has been long deleted. Card numbers and ids will be discussed fully In a later chapter.) You won't always want to reach for the keyboard to view an adjacent card, however. Many HyperCard applications will be almost entirely mouse-driven, particularly during information retrieval tasks. Most stacks provide buttons that let you leaf through cards one at a time. For Finding and Entering Information 47 example, on the Address card stack, clicking the Browse tool on the fat left- facing arrow "flips" one card one so you can see the previous card; clicking the right-facing arrow flips forward to the next card (Figure 2- 4). In case a stack does not automatically provide this Idnd of navigation, you will be able to modify Its cards to include such buttons. Instructions for doing this will be provided in Part Two. Where do I Click? ^ ' ' If you're ever at a loss about where to click on a card, you can look at the locations of all buttons on the card, even if the buttons are completely transparent ("see- through"). Press the Command and Option keys at the same time. Outlines of all buttons will appear on the screen. You may discover buttons you never knew were on a card. Finding Text A much more sophisticated way of finding desired information Is to let HyperCard search all the cards in a stack for a particular series of text characters— a text string. HyperCard can search text in any text field on any card In a stack for a match to a string you specify. HyperCard's bHndingly fast searching capability actually encourages this kind of search. For HyperCard to search for text, it must, of course, be told what text characters It is to look for. That's where we again meet the Message Box. FINDING AND THE MESSAGE BOX > To make HyperCard look for a match to a text string, you must enter the Find command into the Message Box, plus the string, which must be inside quotation marks. Fortunately, HyperCard provides a shortcut for typing the find command. By choosing Find. . . from the Go menu, or Figure 2-4. Many cards have buttons to get to previous and next cards with the mouse. 48 Browsing Through HyperCard > ;j by typing Command-F, HyperCard automatically enters the Find com- ; . ) mand and the two quotation marks into the Message Box (if the Message Box Is hidden when you Issue the Find menu command, It shows itself). Moreover, the flashing text Insertion pointer is preset ,•; o,' between the quotation marks. All you do Is start tjqjing the text string you wish to find. The text between the quotation marks is called the /ind string. Then, as with any command, press Return or Enter to carry out the search. HyperCard searches every field in the current stack {that is, the stack you're viewing at the moment) for the first occurrence of the find string. Upon finding a match, HyperCard displays that card and draws a box around the text In the card that matches the find string. Figure 2-5 , ' . , shows the results of a search in the Address stack for the find string ■ t , "Andrew." ;,[''' In the time it takes HyperCard to find a match, the cursor changes ' from the Browse tool to the Beachball cursor (Figure 2-6). The ball appears to spin as the search progresses. You'll also see the Beachball when the program is busily churning away on certain other HyperCard operations. HyperCard starts its search with the card you're viewing when you ' ' ' type text into the Message Box. If you have Just opened the Address ■ stack from the Home card and entered a Find command Into the '" ' ' Message Box, HyperCard begins its search with the first card of the ' - stack. But if you issue the Find command without changing the find ' ' " string {that is, by simply pressing Return with an existing Find command already there), then the search begins with the card following ' the one you're viewing. Let's explain. HyperCard is aware that a search for text may result In more than one match. Once you've built up your own name and address stack, for instance, a search for the common name John will surely turn up multiple matches. To speed your way to viewing all possible matches ■! :> i^. ; foj. a j^nd string typed into the Message Box, you can continue to press • ^ ' ' '''' the Return or Enter key. Each press causes HyperCard to carry out the . - ' game Find command it just performed, but starting with the next card ' '■■ in the stack. You can use this knowledge of HyperCard's inner search workings to your advantage if you're in a hurry to find a particular card and don't want to spend time typing in the full text for which you're searching. If your name and address stack contains 200 cards, and three of them are for people whose first name is Linda, you can cut your typing chore by simply typing "Linda" as the find string, instead of Linda's full name. HyperCard will begin its search for a text match. If the first match is not the one you want, simply press the Return or Enter key again. Keep Finding and Filtering Information 49 4 File Edit CD Figure 2-5. When HyperCardfmds a match, it draws a box around the matching text. . , . , . Figure 2-6. The Beachball cursor ' . -.• c-f ' .': pressing either of these keys until the desired card appears. By drawing a box around each "Linda" found in various cards, HyperCard draws your eye to the appropriate Information in the card to help you more readily Identify the correct card when you land on It. HyperCard searches the stack quickly enough to make this both a time and typing shortcut. HYPERCARD REMEMBERS FIND STRINGS -m- If you've opened stacks that have built-in Find commands (that is, Find commands are carried out in scripts behind the scenes), you may discover text already inserted into the find string when you choose Find... from the Go menu or type Command-F. The reason for this is that HyperCard remembers the last find string it searched for, even If 50 Brvivstng Through HyperCard other kinds of commands or calculations have been entered Into the Message Box in the meantime. If HyperCard has performed any kind of Find command since you last started up the program, the most recent find string will appear in the Message Box (Figure 2-7). When such text appears, It Is automatically selected. Following Macintosh text editing conventions, you may simply type a new find string. The selected text will be erased. Here's one more related shortcut. Once you have issued a Find command, the find string Is no longer selected. If you then want to type anotlier find string into the Message Box, type Command-F (or choose Find... from the Go menu). This action selects the current find string, allowing you to start typing a new string to replace it. All in all, there is little need to select or edit find strings manually. It's usually faster to type Command-F and type a new string in its place. Now that we've looked at some of the theory of finding information, let's look at specific examples. # File Edit find "andrew" Figure 2- 7. HyperCard remembers the last find string it searched for, even if the find was done by a script Don't be alarmed whenfind strings already appear Finding and Entering Infonnation 51 EXPERIMENTING WITH FIND To bring our examples to life, we'll use a hypothetical stack that resembles the Address stack on your HjrperCard disk. In this stack are five cards with friends' names on them, plus a cover card, similar to the one hi Address. A representation of the stack and the five names on its cards is shown In Figure 2-8. We've sorted these cards according to the last name in the first line of the text field, precisely the way the Address stack's Sort button does it. Since there is no text on the first line of the cover card. It sorts out as being first. John Atkins Is the next card In the stack. When we start this stack from the Home card . the cover card Is the first we see (Figure 2-8), along with the Message Box poised to receive a find string. If we wish to see if there are any other cards with the name 'John," we type the name into the find string and press Return (or Enter). HyperCard begins searching with the current card and flips to John Atkins' card, drawing a box around John Atkins' first name (Figure 2- 9). Pressing Return again sends HyperCard on a search through the stack. Since HyperCard is looking for a match for any group of text starting with the letters J-O-H-N, the search stops on Tom Johnson's last name, with a box drawn around the full word (Figure 2-10). Jon Taylor [Tom Jones Chris Jones Tom Johnson John Atkins My Address Stack Ffgure 2-8. Simple stack setup for a FWD experiment 52 Browsing Through HyperCard •'fin • • -. '.tr ~- Figure 2-9. Searchlngfor "John" stops on thejirst card in the stack with a match, HyperCard draws a box arourul the matching text. Notice this result. Unless otherwise instructed by way of a command (covered in chapter 21), HyperCard searches at! fields of the stack for an occurrence of the find string. By drawing a box around the found text, however, HyperCard makes it easy for you to quickly see whether the text you're looking for Is In the right place. Therefore, if you're looking for a first name and HyperCard finds the text in the last name, you'll see at a glance that this card does not apply to your immediate search. Time to press Return again. Another press of Return, and HyperCard searches once more. This time, it doesn't find another instance of "John" in the remaining cards. But, since a HyperCard stack is cyclical, it continues its search through the stack again, stopping on John Atkins' card (Figure 2-9). To demonstrate this further, let's say you want to find the card with Jon Taylor's name on it. The spelling of his first name precludes searching for "John," although if you forgot that Taylor's name had this variant spelling, you may have difficulty searching for his first name. If you knew how to speU Jon's name, you could search for "Jon." Doing Finding and Entering Infommtlon 53 Jon Taylor Tom Jones Chris Jones TomlJohnsonI Figure 2-1 0. Another press of Return, and HyperCard finds the next instance of "John" in the name "Johnson." so, however, will cause HyperCard in this stack to stop on three different names, two of which have "Jon" as part of their last names, the Joneses (Figure 2-8). You could search for Just "Jo," but in this stack, HyperCard would stop on each card. At the other extreme, you can be as specific as you want to find text in a card. Note that In our sample stack, two cards have the first name of Tom. The easy way to find Tom Jones, would be to type "Tom" into the find string and continue to press Return until his card appeared on the screen. But If you're not afraid of typing more letters into the find string and prefer to race immediately to the desired card, you can type the full name into the Message Box. HyperCard won't bother stopping until it finds a match for the entire content of the find string. Continually pressing Return in this case will cause HyperCard to search the entire stack again, winding up at Tom Jones' card each time. One other case we haven't explored yet Is searching for a name that Is not in the stack. If you searched the above stack for "Steve," HyperCard wouldn't find any cards to match. To confirm that it 54 Browsing Through HyperCard searched for the find string, HyperCard will flash the Beachball cursor during the search and then beep once. The purpose of these exercises is to show you that the more specific you can be in your search, the more efficient the search wUl be. HyperCard, as you've seen, is quite accommodating if you prefer to be general. Tliis actually gives the program enormous power, since It doesn't force you to remember details. Even if you have only a sfight recollection of the information you're searching for. HyperCard will let you quickly browse through the stack to find exactly what you're looking for. Naturally, the more specific you can be in your search request, the quicker HyperCard will reach the desired card. Whenever possible, search for items that are more unique than general, such as searching John Atkins' name by speciiylng "Atkins" as the find string instead of "John," which will likely have many matches. HyperCard's text search works faster when you specify a search string of three or more letters. NARROWING TEXT SEARCHES The more information you place In the find string prior to a search, the quicker HyperCard will find the desired card, as we've shown. But what isn't obvious is that when you type two or more words into the find string, HyperCard is actually seairching for a card that contains both words anywhere on the card, not just side by side. You can use this feature to narrow a search by looking for the occurrence of words in different fields. Suppose you return to your office and find a badly garbled answering machine message waiting for you. About the only words you can pick , : out are the last name, Johnson, and the area code of the number to call, J 312. If you want to check for all the Johnsons In your name and address file located in the 312 area code, you would tyipe the following search ,,. message Itito the find string: Johnson312- ; ^-j, , , If you had typed Johnson only, HyperCard would stop on every Johnson in the stack; typing only 312- would make it stop on every phone number in the 312 area code. But by specifying both names . , ' separated by a space , you instruct HyperCard to stop only on cards that meet both criteria. If both words are at least three letters long, then HyperCard performs Its fastest search. TTils may also explain those rare occurrences when you can't figure out why a HyperCard search displayed a card that didn't appear to match. For instance, if you search your name and address stack for someone named John Street, HyperCard will find all occurrences of Finding and Entering Informatk>n 55 cards with both "John" and "Street"— which could be a lot of cairds. In practice, this shouldn't happen too often, but this aspect of HyperCard multiple-word searches may explain some apparently anomalous behavior. PICKING UP TEXT -iH • -^^v- -^-^^ v ' You may also enter information into a find string directly from text already in a HyperCard text field. The procedure Is called picking up text. Normally, when you position the Browse tool atop a text field, the cursor turns into the I-Beam text cursor. If you hold down the Command key at the same time, the I-Beam turns back into the Browse tool, whose hand "picks up" text when you press the mouse button. With the Command key held down, click on a single word, HyperCard flashes a box around the whole word and places that word Into the Message Box {Figure 2-1 1). Click and drag across a few words, and the box around the text grows as each word Is added to the Message Box, To Do ..P.honeJex.e.miah.Adam .Pick.ufl.cleaninfl .Create, overhead. ierr!pj.ates ..Quarted.y...nne.et1..n.g .C.aJ..1iDa.Ki.d|.M.Q.rg.e.n.th.a.]., David Figure 2-1 1 . Picking up a single word by Command-clicking it 56 Browsing Through HyperCard The efficient way to use this technique for finding text already in a text field is to type Command-F and pick up the desired text. It goes directly into the find string. Typically, text pick up is used to find the occurrence of a text string in a different stack or background. Therefore, if you find a name on a To Do List, you can pick it up, navigate to the name and address stack, and press Return to find that person's phone number (Figure 2-12). Similarly, you may also pick up the phone number and click a dial button, which sets in motion auto-dialing of whatever number is in the Message Box, Entering Text Information , ' Wliile you'll probably use HyperCard more for browsing and retrieving information than any other action, it will also become a repository for new information you wish stored in your computer. After all, what good is a name and address type of file if you can't add names and addresses to it? ^^^^^^^^^^^^^^^ To Do ..P.hQ.Qe. Jeremiah. Ada ..P.i.Q.K..!JP...P.j.sin.lr!S ..Create. oyerhead.lempJ.a ..Qu.a.rte.r].y...rn.e.e.ti..n.g .C.a].J.lDayi.d..M.o.rg.|jj)j;.h.3.] find "David Morgenthal" Figure 2-12. Convnand drag over the text to pick it up prior to a search. Finding and Entering Information 57 FIELDS, AGAIN Earlier we described how a field fits Into the big picture of HyperCard. Fields are strictly for text entry and storage. A card may contain only graphic information, such as a piece of clip art, so there is no law that says a card must contain fields. But practically every card in your stacks will contain at least one field. Even a clip art stack wUl probably have a field with a text description of the object. That way, you'll be able to have HyperCard search a potentially huge clip art file for Images In a particular category or images of a particular item. As we'll see in chapter 9, specifications about a card's fields are established in HyperCard's authoring mode. Field specifications that will be obvious to you as you enter information into a card are such things as the location on the screen, the horizontal dimension (how "wide" it is on the screen), the number of text lines, the font type, and the font size. If you are using a stack that has been authored by someone else, these decisions have been made for you, although you will probably be able to adjust fields as you see fit. THE TEXT CURSOR - • ,.-..,-/; To help you enter text into a field, HyperCard automatically changes the Browse tool to an I-Beam cursor (Figure 2-13). This is identical to the cursor you have probably seen In other Macintosh text applications. September 2 1 ^ i 2 Figure 2-13. The Browse tool turns into the I-beam when it enters afield. Upon leaving the field, the tool returns to the Browse tool. 58 Browsing Through HyperCard FINDING A CARD'S FIELDS Unlike a paper form, which usually has a blank line or box that you are to fill In. a HyperCard field may not be so obvious when you are just looking at the card. For example, when you look at a blank card from - a stack, It Is not immediately clear how many fields have been created for the card or exactly where they are on the card (Figure 2-14). Nor can ->ui you be certain that text you see on a card is in a field or text In the background, like the preprinted portion of a form. Fortunately, you have a couple of ways of finding where a card's fields are. i The simplest way to get started in your search is to watch the cursor as you move it around the screen. Wherever there is a text field to which you have access, the Browse tool turns to the I-Beam. ■V Click the mouse button anyplace the cursor is the I-Beam. The text c insertion pointer will appear and flash at the left margin of the field In y c: the same line of the field as you clicked (the text pointer may also flash >■ in the center or at the right margin, however. If center and right alignment had been assigned to the field when It was created). You may type text if you wish. To find other fields In the card, simply press the Tab key a few times. If no text has been entered Into any field, you will see the text Insertion s>i pointer flash at the beginning of each field on the card. Fields, as you wUl discover In chapter 9. have an order on the card, just as cards have Royce Walthrop 217 Crocker Lane Hillsdale, Ohio 44704 (216)555-3452 Work: General Sprocket (216)555-7554 c Figure 2-14. How manyjields are there on this card? How many lines are there in each field? Finding and Entering Information 59 an order in a stack. As you press the Tab key, each field tn its order becomes activated and is ready to accept text typed from the keyboard. Because the order of fields does not have to follow any prescribed geographic order on the card, it is possible that as you press Tab, the fields activated in turn wiU be all over a card. If text already occupies a field, then a press of the Tab key that activates that field selects the entire text in the field. Following the Macintosh text editing conventions, selected text means that it is ready for cutting or copying into the Clipboard. It also means that a press of any key wlU replace the original text with that new key (reversible by choosing Undo from the Edit menu) . A second way to find the fields of a card requires us to skip ahead for Just a moment to another tool on the tool palette: the Field tool (Figure 2-15). You can access the Field tool only when the user level Is set to Authoring or Scripting. When you choose the Field tool from the Tools menu, HyperCard shows outlines of every field on the card (Figure 2- 1 6) . If a field has more than one line, the field is shown with the locations of its multiple lines and the spacing allocated for each Une, according to the font size defined for that field. ENTERING AND EDITING FIELD INFORMATION If you've done the least amount of word processing or text entry In another Macintosh application, you'll feel right at home entering and editing text in HyperCard fields. Wherever the text insertion pointer flashes in a field, the next character you type will go into that spot (Figure 2-17). When you've finished typing text for one field in a card, you can proceed to the next field either by pressing the Tab key or by using the r — T 1 1 L _ J 1 1 o O A O Figure 2-15. The Field tool 60 Browsing Through HyperCard bit Bpyce.Wajthrop.., 217Xrocke.rLa.ne Hi]lsdale,..Ohio 4470^ (216.)..555-,3452 Work :.,G ene ra ] Sp.rock e t 12161.555-7654 St Figure 2-16. With the Field tool selected. eachJleldS outViws and text lines appear. Archiba V.I . r '.id. t>i i ,---1 1^ Figure 2- J 7. The Jiashing text insertion pointer shows you where the next character you type will appear in thejield. Findtng and Entering Information 6 1 mouse to point to the next field and clicking. Since text entry is by keyboard , it is far more efficient to progress through fields using the Tab key. HyperCard text fields follow most editing conventions of the Macm- tosh user interface, as described in your Macintosh owner's manual. Selecting text for cutting and copying to the Clipboard, pasting from the Clipboard, and undoing your last operation hold true for HyperCard fields. Note, however, that the font type, font size, and style (for example, bold, italic) are fixed for an entire field. You cannot, for instance, italicize one word in a field. CREATING A NEW CARD , , . . ; .„7 Except for those cases in which you need to modify text in an existing card, most of your HyperCard text entry will be into new cards. Creating a new card is a simple task in HyperCard. Open the stack in which you wish to create a new card. Find a card that has the same background you wish the new card to have (some stacks may have more than one background) . On most stacks, you can use the first card that appears when you open the stack. Next, choose New Card from the Edit menu or type Command-N (Figure 2-18). HyperCard displays a card without any text or any foreground graphics (for example, a piece of clip art) . If the card has a text field, the stack may automatically place the text insertion pointer at the first field of the card, but this is not true for all stacks, depending on the stack author's ideas. ■J' . ■ -H)) ; ; Undo 3gZ Cut SgH Copy •. §§c Clear Neiii Card Delete Card Figure 2-18. Create a new card with New Card in the Edit menu. 62 Bmwstng Through HyperCard > - ; The card Just created was placed In the stack In order right after the ' t card you were viewing when you created the new card. If the stack provides a sort button, it's not critical that you create a card In Its final - : • place In the stack's cycle. t. iUT'. It's quite possible that until you develop a routine for creating new ■u\ ( - cards tn your stacks you will accidentally create a number of new cards ■ ; . V that carry no text. This will be especially true if you are accustomed to entering Information Into more traditional database programs on the ^;T- Macintosh or other computers. The reason is that you will feel as if you f-«j must "enter" the Information for it to be duly recorded and saved on the disk. In database programs, this action usually entails pressing the Return or Enter key, which clears the form on the screen. Tliat's not the case with HyperCard. HyperCard automatically saves your card's freshly typed Information '\iv \ i. to disk the minute you do one of the following: - - !iO j'B , press the Enter key b/i ot * ^(iv^^nce the text pointer to the next field with the Tab key or mouse > ; :> 1 ! • chck the Browse tool outside the text field ii \< , change the cursor to any tool other than the I-Beam • make a menu selection • pressaleft- or right-arrow key on the keyboEird to view an adjacent ■^!:-': .b- card in the stack - -^.q-- • click the mouse pointer Inside the Message Box • create a new card Therefore, HjrperCard covers you by saving your Information when- ever you risk losing it. In fact, you'll notice that there is no Save command in the HyperCard File menu, unlike other Macintosh pro- grams. HyperCard takes care of saving and updating for you automati- cally. DELETING A CARD } i You can delete a card by choosing Delete Card from the Edit menu (Figure 2-19). Note that this action deletes the card you're viewing when you make the menu selection. When HyperCard removes the card, you'll be viewing the next card in the stack, just as if you pulled a card tn a card catalog drawer: The next one in line would be visible. If you need to delete several consecutive cards in a stack, start with the card nearest the front of the stack. That way you'll be able to delete successive cards rather quickly. HyperCard intentionally has no keyboard command for deleting cards. You must make a conscious menu choice to get rid of each card. Finding and Entering Information 63 Edit ^^^^^^H Undo mz Cut " Copy 3€C mi Clear New Card Delete Card Figure 2-19. Delete a card with Delete Card in the Edit menu. CHAPTERS HyperCard Linking and Printing We finish our guide to the HyperCard browning environment by demonstrat- ing more sophisticated methods of finding information that may be built into stacks provided by Apple and others. We'll also explain in some detail how to take the fullest advantage of HyperCard's extensive printing functions. , >; 'fyfj^if;: Cwss-Reference Information ' As we discussed in the Introduction, there are many cases in which a search for Information must branch away from the current, specialized body of knowledge. Buttons, as we hinted in chapter 1 , give you that kind of branching power in HyperCard. When you combine text, the Mess^e Box, and buttons, you have an incredibly powerful browsing capability at the tip of your mouse finger. Buttons, of course, can be instructed during the authoring process to perform many different tasks. Not all buttons are joined with find strings in the Message Box, but we'll look at one such combination to demonstrate effortless searching among seemingly unrelated stacks. Our demonstration falls under the broad guise of linking stacks. We'll have much more to say about linking In chapter 1 1 . For now, however, you can think of a link as one of those colored yams that jumps across traditional boundaries of groups of information. Actually, a link 65 66 Browsing Throttgh HyperCard (a) il 4Q; (b) Figure 3-1. Unks are like yams between cards in a single collection (a) or between cards in different collections (b). between stacks is more like a yam between two different bulletin boards, each board consisting of cards detailing a separate body of knowledge (Figure 3-1). THE MESSAGE BOX AND LINKING When a card contains a button that links to another stack, it often needs some search text in the Message Box before it jumps to the other ! . Stack and begins its search. As you may recall, if you hold down the Command key and click the Browse tool atop any text in a field , it picks up the text and copies it into the Message Box. You should be aware that the Message Box is very much alive, even when it is not displayed on the screen. HyperCard keeps the content of , K the Message Box Intact at all times the program is running. As an extra is, level of feedback that things are, indeed, working as you expect, the Message Box shows itself the instant you begin picking up text. As a result of the automatic placement of text into the Message Box and find string, a search into another stack can be accomplished with Hi--: the mouse, provided the button that branches to the other stack has HyperCard Linking and Pnnttng 67 been given the proper instructions during its authoring session. A button so empowered will usually perform the following actions: • open the other stack • start a search for the text In the find string In essence, then, the button switches stacks. Inserts the Message Box text Into the find string and does the equivalent of pressing the Return key to commence the search. HyperCard takes over from there. If a match is found, HyperCard brings that card Into view and draws a box around the matched text. If it's not the exact card you expected, you can continue pressing Return as HjrperCard checks further through the stack for the text originally placed into the Message Box. INTELUGENT LINKS Another style of card linking is exemplified in the HyperCard stack called Datebook. This stack is represented on the Home card by three Icons: To Do, Weekly, and Calendar (whose background is named, "Six Monthly") . These three applications are actually combined Into a single stack with three backgrounds. Still, there is a sophisticated structure established to link the Weekly and Calendar parts of the stack. In the Calendar application, for example, you can cHck the Browse tool on any week of any month showing in the six- month spread (Figure 3-2). A rather complex script calculates which week you've clicked on and then proceeds directly to the weekly appointment card for that week. These two applications could just as well have been In two separate stacks, yet the operation would not be affected by that file arrangement. Links of this nature not only bring two applications together but take the extra steps to eliminate manual searching on the user's part. The more a link action anticipates your next moves and appears almost magical, the more care has gone into designing the Unk. OTHER UNKING POSSIBILITIES M ^ x^ In later chapters, you wiU see that linking is one of the powers of HyperCard that makes the program behave unlike any other software. For example, HyperCard can send along Information during a link-up. Your Address stack, for Instance, has a button on it with an icon of a telephone. When you click the phone icon In an Address card, Hyper- Card jumps to the Phone stack where a special- purpose card Instructs a telephone modem to dial the number in your Address card. Thus you have an automatic dialer at your fingertips. 68 Browsing Through HyperCard □ % 1 2 3 'I 5 6 7 3 9 10 U 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 23 29 30 31 October 12 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 23 29 30 12 3 4 5 November 6 7 3 q 10 llnl2| 13 14 15 16 17 ISTF : .. 20 21 22 23 24 25 26 , 27 28 29 30 31 ; December ^t"»"al papor fBBri rnnif>s: |||| 11 ^ J Fast laser printinq r — ^ ^ 1 Cancel 1 n No space betuieen cards O Print one card per page O Print full size cards O Print hair size cards ® Print quarter size cords (§} Standard format O Split-page format Header: H) ^ ^ ^ Fig we 3 -8. Specifying quarter- size cards on the Las erWriterprod uces thirty - tux> readable cards per page. Browsing Through HyperCard Print Stack... □ Manual paper feed ^ Fast laser printing Header: ii} ^ g| ^ Copies: I r r mm e e mm ; mm r r Wm S Cancel □ No space between cards O Print one card per page O Print full size cards ® Print liaif size cards O Print quarter size cards O Standard format <$) Split-page format Figure 3-9. Split- page Jormatting leaves room for hole punching and insertktn into loose-lecif executive organizers. One other format option is whether you wish to have white space between cards on the page (Figure 3-10). This will be a personal choice and will often depend on the design of the card backgrounds and whether you like the visual reconfirmation of each card being an independent unit. The long text box at the bottom of the dialog box is the place you can type in the text for any header you would like to print at the top of each page. Header text prints In the Helvetica font on the LaserWriter or in a plain, built-in font on the ImageWrlter. All text Is left-Justified and appears in miniature at the top of the sample page in the Print Stack dialog box. To the header you can add the time (the time of printing), the date, a page number, and/ or the name of the stack file. You do this by first positioning the text insertion pointer in the header box where you wish to add one of the elements. Then click the icon for the desired data you wish added to the header {Figure 3-1 1). Stack printing on the LaserWriter starts with the last page so that the finished pile of printed pages is automatically sorted from front to back in the paper output tray. While the stack is printing, you can cancel the process at any time without having to finish the entire stack. HyperCard Linking and Printing 75 Print Stack... □ Manual paper feed lEI Fast laser printing Header El ^ Copies: OK [ Cancel" ^ No space betufeen cards O Print one card per page O Prtnt full size cards ® Print hair size cards O Print quarter size cards O Standard format ® Split-page format Figure 3-10. Selecting no white space between cards scrunches the cards together on the page, : . Print Stack... n Manual paper feed 1^ Fast laser printing Header: j] ^ Copies: I [ Cancel"] □ No space between cards O Print one card per page 1 iwr'n i...A ; I::..!!,;*] Print toHt fields from all cards: O in ihe. eniive ^Im'.k lUtth the current background Ullilch fields: Selected background fields: _ Figure No, Caption Print the names of: □ Cards S Fields Figure 3-12. Print Report dialog box set to print JieMs in columns HyperCard Unkir^ and Printing 77 wish to be included in the report. If the fields are named (most fields in Apple's stacks and third-party stacks are named) , the field names wUl appear tn the field listing. When a field lacks a name, its place is held by the word Field and a number indicating its order among all the fields. To choose Individual fields but not all fields, hold down the Shift button and click on each field name you wish in the report (Figure 3-12). Importantly, field information will appear in the report in the same order as you Shift-click their names in the scrollable field name box. Hs^erCard initially allocates equal width for each column, based on the number of fields in the card. You can, however, drag the dotted dividing lines left or right to make columns as wide or as narrow as needed. If information tn the field is longer than the column is wide, the text "wraps'* to the next line in the same column during printing. Two additional options let you print card names (which adds an extra column— see Figure 3-13) if the cards in the stack have dlff'erent names (most of the time they don't have any name) and print field names. If the field names In the scrolling box have real names (instead of Field 1 , Field 2, and so on), printing the field names will probably be a good idea, because the names become headings for the columns. As you select background field names to be Included in the report, their names appear in the miniature replica. i;-j.r r . ..n ' Print report... Copies:[[ □ Manual paper reed Header: g^] B) H $ Hrrange fields in: O Labels (D Columns O Rows: Cancel |j(t: Print tewt fields from all cards: O In the entire stack ® Ullth the current background lifhich fields: □ Card fields 1^ Selected background fields: Figure No. Caption Print the names of: ^Cards 1^ Fields Figure 3-13. When you print card rtames aiong with flelds, HyperCard prints an extra column for those names. 78 Browsing Through HyperCard If you specify that the fields be arranged In rows, each card's Information is grouped together, as indicated in Figure 3-14. You can print card names and field names if you wish, although field names are probably the more common selection when the fields are named descriptively. If the field names are long, you can drag the dotted dividing line in the miniature page to make appropriate room. An example of the printout of a couple of cards is shown in Figure 3-15. Another choice is to print in rows and in two columns, as shown in Figure 3-16. When you make this selection, you have yet another choice to make; the layout order. The middle and right-hand schematic layout diagrams (next to the Rows button) indicate in which order card Information will be assembled on the page. Numbers in the diagrams stand for the order of cards. The left diagram indicates that the cards' data will be printed iirst down the left column and then down the right column. The right diagram indicates that the printing layout order will be from left to right. Figure 3-17 demonstrates the difference. You may also choose whether the report should extract text iields from all backgrounds in the entire stack or from only the background you were viewing when you chose Print Report in the menu. If you elect to print the entire stack, you lose a great deal of your report format control, because HyperCard won't know what fields to expect in other Print report... Copies:[| □ Manual paper feed Arrange fields O Labels O Columns _ □ Card fields ^ Selected background fields: Figure No. Caption [Field 4 Print the names of: n Cards ^ Fields Figure 3-14. Laying out JishcLs in rows gives the information an entirely different look and organization on the page. HyperCard Unking and Printing 79 My Address Book — Page 4 —i .1 Name and Address: Phone Number: Name and address: Phone Number: Name and Address: David Ogborn 2119 Runnymede St Tempe, Arizona : - (602) 555-6692 Edmund Reid * — - - 6080 Nicole Place Monterey, California (408) 555-0406 Beverley Richie 1250 Washington Avenue Gettysburg, Pennsylvania (717)555-8454 Phone Number: FJgure 3-15. Sample printout of a verticaUy oriented report Print report... Copies: j □ Manu&l paper feed Arrange fields in: O LBbeis O Columns ® Rouis: [ Cancel""] mm ma] Print teHt fields from^aii cards: O In the entire stack ® LUith the current background LUhich fields: □ Card fields 1^ Selected background fields: Figure No. Caption BSSi Field 4 lii Datp Header: ^ E) H ^ Print the names of: □ Cards ^Fields Figure 3-16. Row format also allows printing in two columns. 80 Browsing Through HyperCard 8 8 Figure 3-1 7. Row printing in two colwnns may be organized in two different ways, depending on which icon is selected in the Print Stack dialog box. backgrounds in the stack. They may be totally different from the current stack's fields. The default setting is for the current background. This is the choice you'll make almost all of the time. Next choose whether the report should contain card (foreground) fields or selected background fields. Most cards you'll browse through will have background fields only, so this is a likely choice (for the differences between card and background fields, see chapter 9). You retain the most control over report formatting when you print back- ground fields only. A third report format automatically sets the printout for full -page self- adhesive mailing- label stock (Figure 3-18). You can select which fields are to be included in the printout, as with any print report format. In place of the header information are specifications for label size. By dragging the black square "handle" in the lower right comer of the top label, you can adjust the size of the miniature label to match those of the label stock you plan to run through the printer. Drag the top left and bottom right labels to adjust label margin spacing and spacing between labels. There should be adjustment to accommodate most standard label stocks measured in inches or centimeters. HyperCard Linking and Printing 8 1 Print report... Copies:pU| □ Manual paper feed 1 — J Dimensions: finches Qtm [m 0.25 Arrange fields in: (i) LabeJs O Columns O Rows: OK 1 [ Cancef"] Print teKt fields from all cards: O In the entire stack <§) Ulith the current background Ufhich fields: □ Card fields [gl Selected background fields: Figure No. Caption Field 4 Date 0 O 2.5 1^ 0.0 ::iE] 0.125 Figure 3- 18. Formatting/or adhesive mailing labels is provided. Drag the handle in the upper left label to adjust printout to actual size of labels. Drag the ktbels to adjust label spacing and margins. Thus ends a whirlwind tour of the browsing environment of Hyper- Card. Even without writing your own HyperCard stacks, you have quite a bit of power available to you . But after using the stacks supplied by Apple and understanding the fundamental concepts behind Hyper- Card described so far, we hope that you'll be Interested enough to pursue developing your own stacks. That's where Part Two begins. PART TWO HyperCard's Authoring Environment C H APTE R 4 Introduction to Authoring If you do nothing more than use the HyperCard stacks that come on your HyperCard disks, you will certainly gain productive use of the program. But you will have only scratched the surface of what HyperCard is all about. True, it is a program that gives you fast access to a variety of information. More importantly, however, HyperCard lets you build the kind of information world that makes the most sense for your work and your life. What Authoring Means to You By combining card backgrounds, fields, and buttons Into meaningful stacks, you can determine the precise contours of your Macintosh World. HyperCard provides many tools for the creation of on-screen graphics that may be metaphors of a familiar, noncomputer world, or you can create useful graphics environments that would be impossible without a computer. With HyperCard you can also establish relationships among numer- ous collections of rnformation. Hie powers of linking stacks to one another goes much further than what commercial relational database programs can deliver. Finally, HyperCcird offers the dedicated user the ability to bring his or her information to life. By applying HyperCard scripts to stacks. 85 86 HyperCard 's Authoring Environment cards, fields, and buttons, you dictate what operations are to take place with each navigational step through H)rperCard. If you've been disap- pointed that a commercial program does not exist for an information management application you have in mind, there is a good possibility that you can mold HyperCard Into that very application. Access to the fundamental building tools— painting, fields, and buttons— is what we mean by the authoring environment of Hyper- Card. Despite the vast powers built into HyperCard, you shouldn't be frightened by them, HyperCard's designers paid special attention to simplifying your access to these powers, even building in a bit of forgiveness here and there to ward off frustration. Still, it may seem that there are many things to learn at first. Just remember that you don't have to learn them all at once. The weekend mechanic more than likely started out as a simple user of the transportation. Only by gradually digging deeper under the hood from one weekend to the next did he leam the impact of various adjustments and maintenance chores. So, too, you began by using HyperCard in the browsing environment, which we've already covered. Now you'll begin to leam little by little what goes on under the HyperCard hood. By the time you're finished with Part Two of this book, you'll know how to buUd applications from the many prepared cards and buttons on your HyperCard disks. In Part Three, we'll dig still deeper into the programming tools buUt Into HyperCard, while learning the basics of HyperTalk and scripts. Part Four will be the advanced course for those who can't wait to get dirt under their flngemails while building Impressive HyperCard applica- tions. Authoring Scenarios There are many reasons why you should actively pursue HyperCard as ' ■ an authoring system. The three most likely reasons are: building your Macintosh World; creating an easy-to-access Information source for '■ ' colleagues and family members; and developing applications for gen- • ' era] consumption. YOUR MACINTOSH WORLD i, . v.- As we mentioned in the Introduction, your Macintosh World consists - *~ of not only the kind of Information you are likely to store in a computer ^ database but also Information you frequently retrieve from outside sources and the documents you create with other Macintosh applica- Introduction to Authoring 87 tlons. You should use HyperCard as a way of extending the reaches of your Macintosh World, Prompted by the Address and Datebook stacks supplied with Hyper- Card, you will probably begin assembling personal information- names and addresses, your daily schedule— in HyperCard stacks. These are practical and among the most obvious applications for HyperCard, But then start using HyperCard as a quick repository for random thoughts and ideas that shoot into your mind. Instead of reaching for the notepad to Jot something down that you hear in a telephone conversation, type it into a stack designed for that purpose. Also, start thinking of collections of personal information which you need quick access to. Perhaps It's a list of hotels and restaurants in cities you visit, complete with notes that remind you of their high and low points. HyperCard is the place you should store the "mental notes" you always make but tend to forget about after a time. Later, use H5rperCard's full text search abilities to track down that thought. Let HjrperCard do the remembering, while you make decisions based on the information stored and retrieved. The more you use HyperCard for these kinds of tasks, the more you wUl find for HyperCard to do. Gradually you may develop "systems," like tickler files, logs of client phone calls, client meeting notes, and so on. Where you have probably failed to start or maintain a paper system in the past, you will have a much greater likelihood of success with its Hj^erCard equivalent, '- ■ STACKS FOR COLLEAGUES AND FAMILY . . You can perform a great service for people you work with, for class- mates, or for others in your family with HyperCard, By creating a HyperCard stack that eases their access to information, you may help computerphobes overcome their fears, A HyperCard stack can be as narrowly focused as needed to accom- plish an Information storage and retrieval task. Therefore, if you can convert budget figures from a spreadsheet into HyperCard cards, and reduce the chore of accessing the information to a series of mouse clicks. Those who normally shun computers may find your HyperCard stack application to be rewarding— even fun. It may encourage com- puter use. In college coursework, an energetic student or professor can create a HyperCard application containing specialized information pertaining to the course or a particular topic. A well-conceived stack of this type, especially with HyperCard's linking and searching capabilities, wUl likely encourage further exploration through the HjrperCard informa- tion base, well beyond flndtng the simple answer to a problem or question. 88 HyperCard's Authoring Environment i. . If you use a Macintosh at home, the family can also benefit from HyperCard applications. The graphical environment is more inviting to , storing and searching various inventories. Record collections, books, appliance maintenance schedules, warranty information— these and many other household records are suited for HyperCard archival. And since you, as HyperCard author, are in control of the way the applica- tion looks, strive for simplicity and graphic appeal to encourage its use by everyone who is allowed access to the machine. GENERAL CONSUMFnON . . ' T • A logical extension of authoring stacks for yourself and others close to ' you is designing stacks for distribution as public domain, user- ; supported, or commercial offerings. • Public domain HyperCard stacks will likely be available from most Macintosh user groups. An author of a public domain HyperCard stack ,. ;.; essentially shares his or her work with the rest of the HyperCard community, expecting no remuneration In return. This is In the best , - spirit of the early days of personal computers and is quite popular today : : > for all kinds of software on all popular personal computers. If you've .1 designed a stack that you find useful, you may wish to share it with - others by uploading via telephone modem to a Macintosh user group bulletin board or by sending a disk to user groups. Another category that relies heavily on user groups and bulletin boards is called tiser-support.6(i software. Such offerings are freely distributed to the user community. The author of a user-supported program usually asks users to try the program at no charge. In a ,, ,, HyperCard stack, this request may be on the first card of the stack. The p : -y message also states that if the prograim Is useful, the user should send the stated sum (usually a low price compared to commercial products) . In return, the user often gets a printed manual, free program updates ; -. for a period of time, and telephone support. Authors of user-supported D . . software have met with varying degrees of success with this method of , J distribution. !-t;j a third option for distributing a stack to the computing cormnunity is to pubhsh it as a software product, either through an established software publisher or on your own. HyperCard offers many opportuni- Ues for nonprogramming Macintosh enthusiasts to get into the soft- ware business. Specialized information stacks wiU appeal to many "vertical markets," which are often best approached by self-publishing. Apple predicts, and rightly so, that HyperCard will spawn a cottage industry of stack publishers . Prior to HyperCard , you had to be almost i a programming wizard to produce a Macintosh application. HyperCard Introduction to Authoring 89 raises every dedicated user to wizard status with much less work and frustration. Remember, too, that you can use HyperCard to create stacks for general consumption that benefit the community. Bill Atkinson (HyperCard's creator) and several colleagues are donating equipment and time to help the Los Gatos, California, Public Library put its entire card catalog into HyperCard. With the help of an optical character reader (OCR), Bill and friends wUl scan the printed cards and convert them to HyperCard cards. Library patrons will be able to perform full- text searches of the entire card catalog in seconds. Although this ap- plication won't be performing many sophisticated button tricks, it will be using HyperCard to its fullest speed-searching capabilities while providing researchers with a way of scouring the entire catalog for needed reference material. The authoring possibilities of HyperCard are rather extensive, rang- ing from the most private to the most public. It's all up to you and your Inventiveness. As we proceed through the various authoring tools in HyperCard, we hope you will be thinking about potential HyperCard applications In your world. Accessing HyperCard's Authoring Tools Back In chapter 1 , you saw the User Preferences card of the Home stack and learned that it controls access to various levels of tools. Just as we combtned the Browsing and Typing levels into a single browsing environment, so, too, will we combine two more User Levels. This time we join the Painting and Authoring levels into one authoring environ- ment. More often than not, you'U want both sets of tools available to you whenever the authoring Muse inspfres. In the browsing environment, you had three puU-down menus available, as shown in Figure 4-1. For the rest of this book, however, you should boost your user level setting all the way to Scripting. You might get by in the next several chapters by setting the level to Authoring, but we'll be sneaking in some preliminary exposure to HyperTalk programming when you're not looking, and the Scripting setting will be necessary. The menu structure changes when you reach the Painting level. First of all, the File and Edit menus gain several items (Figure 4-2). You also get the Tools menu, as shown on the left of Figure 4-3 (when you choose any of the palnUng tools, three additional menus— Paint, Options, and Patterns— come into view). At the Authoring level, the Objects menu appears (Figure 4-3, right) . These are the menus you'll be using for the 90 HyperCard's Authoring Environment remainder of the book. The Scripting level doesn't affect the menus in any way: Its changes are more subtle. Still, set your user level to Scripting now (Figure 4^). For the time being, ignore the Power Keys . and Blind Typing boxes. We'll get to those later. File ^^^^^^^1 Neui Stack... Open Stack... Sane a Copy... Page Setup... Print Card %p Print Stack... Print Report.,. Quit HyperCard Edit ^^^^^^1 Undo Cut Copy / sec Clear Nem Card Delete Card Figure 4- J . HyperCard's browsing environment menus. New Stack... Open Stack... Saue a Copy. ^0 Compact Stack Protect Stack... Delete Stack... Page Setup... Print Card Print Stack... Print Report. 3gP Quit HyperCard 960 Edit ^^^^^^1 Undo Cut Copy 3§C Paste Clear Neiii Card Delete Card Cut Card Copy Card Rackground see Rack 36" Home %H Help Recent First Sii Preu NeKt Last Find... Message Back Home Help Recent m First Preu NeKt Last 3g4 Find... i§F Message 36M J^l^ure 4-2, Two oj the three browsing environrnent menus change when you graduate to the authoring environment Introduction to Authoring 91 m m 1 1 1 1 1 J ¥ A Jtat "a 1 1 o O c? A O Objects Button Info... Field Info... Card Info... Bkgnd Info... Stack Info... Bring Closer Sg+ Send Farther 38- Neuj Button Neiu Field Neiu Background Figure 4-3. Two more menus. Tools and Objects, cdso come to life in the authoring environment -yj-'^'- fi>):-<^'' ^--m -^z;^- v.-^^ ^j^,t j, ■ . .. User Preferences User Name: Danny Goodman User Leuel: O Browsing O Typing O Painting ^ PoLuer Keys O Authoring ® Scripting lEI Blind Typing Figure 4-4. Setting the user level to Scripting 92 HyperCard's Authoring Environment The HyperCard Screen HyperCard appears differently on the screen depending on the size of video monitor you are using with your Macintosh, By monitor size, we mean the number of picture elements, called pixels, or dots, that show on the screen. The pixel measure of a video monitor is usually stated with the number of pixels visible horizontally by the number of pixels vertically. The original Macintosh screen, for example, has a display area of 512 by 342 pixels. The 12'inch external monitor for the Macintosh II displays 640 by 480 pixels. Larger screens are also available that display more than 1000 pixels in each dimension. On the 9-inch diagonal screen buUt into the one-piece style Macintosh (like the original Macintosh and its direct descendants), HyperCard seems to take over the entire screen, with the exception of the menubar at the top. The actual active screen area for HjrperCard, however, extends underneath the menubar to the full 5 1 2 by 342 pixel display area. This allows HyperCard applications to hide the menubar from view, if desired, and take over the whole viewing area of the 9-lnch screen. On larger screens, you will notice that the active HyperCard screen area is actually inside the confines of a standard Macintosh window (Figure 4-5). The window is of a fixed size— it has no grow box at the lower right comer— and does not scroll. When you view the window on a 5 12 by 342 display, you don't see the window's title bar at all. The title bar is "there," but it is located completely above the display space on the small screen. Notice that on large screens, the menubar is at the top of the screen, regardless of the location of the HyperCard window. That's because the File Edit Go 5 * — 51^ 51? v. F^ure 4-5. The HyperCard screen takes up the full 512 x 342 pixieis of the 9-inch Macintosh screen, but it is really a 512 x 342 window, as seen on larger Macintosh monitors. Introduction to Authoring 93 programmer's toolbox inside the Macintosh automatically places menus across the top of the screen. This may help you better visualize what Is happening on the 9-inch screen when menus seem to overlap the very top of the HyperCard active screen area. The menubar belongs to a top layer on the screen that does not interact with the HyperCard window's content in any way. As a HyperCard author, especially if your stacks vdll be distributed to other Macintosh users usmg a variety of screens, you should be very aware of the two ways HyperCard displays its content on both the 9- inch monitor and larger monitors. For example, if you design a stack using a big screen monitor and place important information, such as a field or button, near the very top of the HyperCard vrindow, another user with a 9-inch screen may have part of that Information obscured by the menubar. As a rule, you are safer designing stacks for the smaller displays, because they are the predominant style in circulation.and should be so for several years to come. HyperCard Menu Types While authoring a stack, you will make heavy use of the standard HyperCard menus. Most of the menus contain commands that assist you in building your application. We'll gradually cover the commands in detail as we begin building sample applications later in the book. STANDARD MENUS J, ' ; . , : Most of the menus In the menubar behave just like menus you've encountered in other Macintosh applications. A number of choices in the menus are available from the keyboard by pressing the Command key and a character key (Figure 4-6). You don't have to leam the keyboard shortcuts right away. As you start using HyperCard more frequently, you will notice certain commands that you use often. If these commands have keyboard equivalents, try performing the com- mands from the keyboard when you remember to do so. Slowly, you'll find keyboard commands to be practical shortcuts, particularly If you are In the middle of a lot of keyboard work. TEAR-OFF PALETTES HyperCard also introduces a new kind of menu to the Macintosh repertoire of user Interface issues: the tear-off palette. Two HyperCard menus. Tools and Patterns, are of this new type. To begin with, these menus pull down like other menus, except that they reveal choices of 94 HyperCard's Authoring Environment Go ^^^^B Back 3§~ Home 3€H Help 3e? Recent 3iR First 961 Preu ^2 NeKt |g3 Last 964 Find... §§F Message 3€M Figure 4-6. Many menu commands may be activated by typing the Command- key equivalent listed in the menu. graphics items instead of text items. You pull down the palette from the menubar, make your selection, and release the mouse button to remove the menu from the screen. But since you are likely to make frequent selections of tools and patterns while authoring, HyperCard lets you "tear off the palettes from the menubar and drag them as free-standing windows anywhere on the screen where it's convenient. To do this, simply pull down the menu as usual, but then drag the mouse pointer completely off the palette that dropped down from the menubar. As you drag the pointer, you will see an outline of the palette follow the cursor (Figure 4-7). When the outline is in a suitable location, release the mouse button. The palette will shift from below the menubar to that new location (Figure 4-8). Tear-off palettes turn into small windows when they are detached from the menubar. To remove palettes from the screen, just click the mouse pointer In the close box on the window's title bar (Figure 4-9). If one or both palettes is already detached from the menubar and you reach for the palettes from the menubar, HyperCard will oblige, showing you both the menubar and detached palettes at once (although you won't be able to tear off two copies of the same menu). Use the palette that Is most natural at any given moment. Next we examine key HyperCard components from the author's perspective. Introduction to Authoring 95 ife File Edit Go ^^^^1 Objects r — T 1 1 L _ ^ 1 1 o o A o cz Figure 4-7. Drag the menu away from the menubar, and an outline of the palette follows the cursor. # File Edit Go Tools Objects BBIo |:;;::::| r — « 1 1 L _ J u o A O a Figure 4-8. The free-standing palette may be moved around the screen to a convenient place for frequent tool selection. 1 1 1 1 o o A O Figure 4-9. Click on the close box to remove the Tools palette from the screen. CHAPTER 5 All About Stacks In chapter 1 , we described the basic properties of a HyperCard stack from the browser's point of view. But we must spend more time discussing the stack concept now, because your perception of stacks changes when you are the author. This is true also for the other basic elements of HyperCard: backgrounds, cards, fields, and buttons. Rest assured that your time in the first chapter was well spent. A HyperCard author must be aware of the browser's point of view for all HyperCard elements when developing new stacks— especially if the stacks will ultimately be used by other people. It's just like a writer who must also be a reader of his own work. While practicing the craft of transferring ideas into words on paper (or screen) , the writer also takes the reader's point of view, questioning each phrase: "Is this stating the idea clearly enough for the reader to understand?" or "Am I conveying the desired emotions to the reader?" Consequently, as we begin our look at the basic HyperCard elements from the author's perspective, we'll also remind you from time to time about the browser— your audience. Two Stack Types ' Our first stop is the HyperCard stack. While we've seen that, technically speaking, a HyperCard stack is a single collection of information, the way you design that collection will vary, depending on the way you 97 98 HyperCard's Authoring Environment present Information In the stack. The two methodologies are what we call homogeneous and heterogeneous, THE HOMOGENEOUS STACK . , . . Probably the most common type of stack you will create at first faUs Into the homogeneous category. As the terra implies, a homogeneous stack consists of a single entity. In the HjrperCard environment, that means that the stack has one card background that pervades the entire stack or system. Perhaps the best example of a homogeneous stack is the Address stack provided with HyperCard. As you flip from the first to last cards, the background "look" remains the same. Only the information you store on each card changes. This homogeneity closely resembles the kinds of "stacks" we're accustomed to In the noncomputer world. The physical name and address book or the dally desk calendar have the same background look to each card or sheet, no matter how large the collection. Only the Information that is specific to a card or sheet— a phone number or the date— changes. A homogeneous stack is most often created and saved on the disk as a single HyperCard stack file. This is not a prerequisite by any means. For example, you may have a very large homogeneous collection that ends up being too large for distribution on a single floppy disk. If that's the case, you will have to break up the collection into smaller flies strictly for ease of distribution, even though the backgrounds of all component files are identical. Another reason to divide a homogeneous stack Is for the sake of modularity In design. The HyperCard on-line help system is an ' ' example. Even though the backgrounds of the Help and Help Index stacks are the same, the system is divided into two stack files. To the browser, however, the help system appears as a single unit. The division between stack files Is completely transparent to the browser. Hie bottom line, then, is that a homogeneous stack appears to the browser as a single stack with a single background, regardless of its underlying stack and file structure. THE HETEROGENEOUS STACK A feature of HyperCard that is potentially of great importance to an author is its ability to combine multiple backgrounds into a single stack. There aren't many examples of this in the noncomputer Informa- tion world (which tends to be homogeneous). But consider a textbook Ali About Stacks 99 that consists of many pages of textual information and a section that consists of color photographs. While the text Is printed on a thin paper In black only, the photographs are printed In four colors on a glossy paper. The "backgrounds" here (thin paper and thick glossy paper) are combined in a single collection (the book). Moreover, the kind of information presented on each background type is quite different. The presentation is a mixed one, heterogeneous in nature. A heterogeneous stack is perhaps best characterized as being more than a simple information collection. Rather, it Is an environment consisting of two or more card backgrounds. Typically, the information stored on multiple backgrounds In such an environment is interre- lated. For example, you may design one background that best conveys the feeling of a table of contents. A second background you designed for the stack contains the actual information cards. Clicking on a button next to a table of contents item calls up one of the information cards (Figure 5-1); a click on a Contents button located on an information card brings you back to the table of contents. The browser has a sense of a single information environment, yet in HyperCard terms, the collection Is a heterogeneous one. HyperCard stacks can be quite heterogeneous. There is virtually no limit to the number of backgrounds you can design into a stack. One of the decisions you will have to make when designing a HyperCard stack that requires more than one background is whether the Information collection Is better served by being divided Into multiple F^ure 5-1. A heterogeneous stack contcdns tux) or more bacf<^rouncls buttt into a single stack JHe. Buttons Unk cards in the different backgrounds. 100 HyperCard's Authoring Environment homogeneous stacks {that is, separate stack files) or a single heteroge- neous stack. If you plan to distribute the environment to others— especially via an electronic medium such as a user group bulletin board— a single, heterogeneous stack makes the most sense. Con- versely, if one or more of the stack backgrounds you supply may grow . to a large collection (such as a name and address background), it may become a disk management burden to lump so many potentially large stacks into one disk file. You should do your best to anticipate the way T you and your stack users will work with your stack over time and choose the optimum stack strategy accordingly. Making a New Stack The prospect of creating a new stack may be a terrifying one the first time out. Fortunately, Apple softens the blow for your early experimen- tation by providing you with a number of predesigned stacks, which you ' can borrow directly. What makes this kind of new stack so simple is the way HyperCard generally creates a new stack. It assumes that for most of the new stacks you will create— especially when you need one In a hurry— you will use either an existing stack or a stack template of some kind as a starting point. HyperCard comes with several such templates on the disk that contains art, card, and stack ideas. Additionally, HyperCard experts will surely be placing their templates into the public domain via user groups and electronic bulletin boards. Stack templates come In all varieties, in terms of content as well as degree of completion. Most of the templates m the HyperCard Ideas disk have a background, background buttons, and background fields. This Is a fine place to start. The steps In creating a new stack— at least getting the foundation firmly planted for later editing and customizing— are simple and few: 1 . Be sure you are at the Scripting level. If you are not, adjust the setting on the User Preferences card in the Home Stack. 2. Bring into view the stack template you wish to adopt (Figure 5- 2). You can do this from an existing stack that already has a number of Information cards in It. The stack creation operation looks only to the background of the current card. HyperCard won't disturb the existing stack or its Information in any way, • ' : AU. About Stacks 101 afe: 9/18 for Royce Walthrop Person Cal/ing Barbara HtiJlan □ Telephoned Company Am^ricgn Widget ^ 13 W)7^ cff// again Ptoe Wo. [301 ) 555-5464 Q Returned your call Message Wants tp tSilK about the □ P/&Gse CO// @ J..a5triC.Ut..sp,rQ.(;Rg.t.5 C] Came to see you □ Wants to see you □ Rush Signed Carl PearsQn □ Special attention Figure 5-2. To make a new stackfrom a template, Jirst bring the template card into view. 3. Pull down the File menu and choose New Stack... (Figure 5-3). A standard file dialog box appears on the screen, requesting a name for the stack you are about to create {Figure 5-4). Unless you have performed some file manipulation previously In this HyperCard session, the dialog box will indicate that the stack you are about to create will be saved In the same disk and folder as your Home Stack. It also offers a choice of whether you want to copy the current background or start from scratch. For now. copy the current background. 4. Type in a name for the stack and press the Return key. This action creates the stack file on the disk for your new stack. Unlike many other Macintosh applications, HyperCard creates the disk file when you start a new document so that it can automatically save any changes you make to it. HyperCard automatically saves your work, most of the time when you don't even realize it. That's aU there Is to creating a new stack. You may not notice anything different on the screen than what you saw when looking at the template, unless the template had sample text typed into its fields. 102 HyperCard's Authoring E^ivironment File ^^^^^HH Nem Stack... ...^ Open Stack... ^ mo Saue a Codu... rfiinnfirt Stark Protect Stack... Delete Stack... Page Setup... Print Card 3ep Print Stack... Print Report... Quit HyperCard Figure 5-3. Choose New Stack Jrom the File menu. Si My Stacks ( HD-20 Ijm-A ] ( : , ' ^ - ■■ ' \ ■ - ■ . New stack name: 1 Neuj > Fone Messages Cancel 1^ Copy current background Figure 5-4. Type in a name for the new stack you are creating. AH About Stacks 103 Such text does not go into the new stack. To prove to yourself that you are looking at your new stack, you can check the Stack Info... dialog box. To do this, pull down the Objects menu and choose Stack Info... (Figure 5-5). This dialog box displays all relevant Information about the stack you Just created (Figure 5-6) . First, It shows the stack name and the folder Objects Button Info.. Field Info... Card Info... Bkgnd Info... Stack Info. Bring Closer 9S+ Send Farther S§- Neuj Button Neuj Field Neuj Background Figure 5-5. Choose Stack Info... from the Objects menu to see the Stack Info dialog box. * File Edit Go Tools I Person Ca Comparr^ Phone No. Message,, rone MeiSiiijes Stack Name: inhere: HD-20 :my stnclcs: Stack contains 1 cards. Stack contains 1 backgrounds. Size of Stack: 10 K Free In Stock; OK { Script.. [ OK ] [ Cancel 1 s you Sigred LI Warrts fo see you □ Special aiieniion Figure 5-6. The Stack Info dialog box reveals data about the stack's back- grounds, cards, name, and stack size on the disk. 104 HyperCard's Authoring Environment pathway to that file. Next, it details the number of backgrounds and cards in the stack. In a brand new stack, both numbers will be one. This dialog box can be very helpful when you begin designing complex stacks, particularly heterogeneous stacks, by giving you a peek Inside the structure of the stack. You can summon the Stack Info dialog box any time you are in the stack whose "insides" you wish to inspect, including the Home Stack. To get used to the information that comes in this dialog box, open a few stacks already on your HyperCard disk and choose Stack Info. . . from the Objects menu. Also in the dialog box is a button labeled Script. . . (if you had set the user level to Authoring instead of Scripting, this button would have been dimmed, denying you access to the script) . You can inspect stack scripts this way on any stack you encounter. UntU we have more to say about HyperTalk, however, "look but don't touch" the scripts in these dialog boxes. WORKING WITH YOUR NEW STACK If the design of the stack you just cloned suits your needs, then you can begin entering information into its text fields right away. Use the techniques you learned earlier as a browser to add new cards and enter text into the fields. You may reduce the user level to Typing, if you prefer. Regardless of the user level selected, you also have available to you menu navigation commands in the Go menu. The most important to remember, perhaps, is the Home command, particularly if your new stack does not have a button that brings you to the Home card. OPENING YOUR NEW STACK One element missing from the new stack exercise is a button on the Home card that opens your new stack. We must emphasize that although the Home card seems to replicate the Macintosh Finder as a way to access HyperCard applications, the Home card does not automatically receive buttons to a new stack. The responsibility for placing a button linked to your new stack rests with you. There are a couple of ways to make such a button, and we'll cover them later in chapter 10, when we discuss buttons in more detail. It's easy to get spoiled into thinking that HyperCard will place a nice button, like an icon button, mto the Home card for every stack we create. Such is not the case. There is some method to this seeming madness, however. If the Home card were to display icons or buttons for every stack on your disk, the card would lose its simplicity. Moreover, you would be forced to look at !t" y; - AU. About Stacks 105 buttons for stacks that don't need them. For example, the HyperCard help system consists of three stack fUes. It's much better to have only one icon button to summon help, and then let the help system drive us around to the various stack files as needed. As you develop more of your own stacks, you will find many cases in which a button to a stack belongs only inside another stack, and not at the Home card level. Endeavor to keep your Home stack as simple as possible. Put only essential buttons on it. The result will be a much less confusing environment in which to grow. Protecting a Stack As a HyperCard stack author, you may have reason to prevent your users from modifying, deleting, or inspecting the scripts of your stacks. HyperCard provides many ways of locking out users from the insides of your stacks if you feel it necessary to make those restrictions. For example, in an application set up as a HyperCard stack running continually In an open environment, like a library or self-service counter, you will probably want to prevent users from deleting or entering information. Such a stack should be limited to "read-only" status. Or you may wish to limit access to browsing and entering Information, but prevent access to authoring and scripting tools. All of this can be controlled via the Protect Stack. . . menu choice In the File menu. The Protect Stack dialog box (Figure 5-7) first lets you determine whether the entire stack (that is, the current stack you are in) can be Protect Stack: - Limit user leuel to: O Brouising □ Can't delete stack O Typing O Painting r O Huttioring ^Priuate Recess ' ® Scripting Set Password ] [ OK 1 Cancel ] Figure 5-7. Protect Stack dialog box 1 06 HypeiCoTxi 's A uthoring Environment O;. '/« deleted. If this item Is checked, a small dialog box reminder appears .'inci 5 whenever the user tries to delete the stack. You may also set the user level for the current stack by clicking one of the five radio buttons next to the list of levels. This setting will not ■A-i r. . affect the user level setting on other stacks. If you are regularly at the J ;; , Scripting level, for instance, and open a stack set to the Typing level, • !. , ihe user level changes only while you are In that stack. The Instant you . ■■i ( u leave that stack, the user level as set In the Home Stack's Preferences card takes over. An important feature to remember is that when you set a stack's user level to Browsing or Typing, the Protect Stack. . . menu entry does not appear in the File menu. That would seem to leave you without any way of getting back to the Protect Stack dialog box to make adjustments you , . might need. The trick, however, is to hold down the Commauid key and then pull down the File menu. You'll see the full File menu, complete ^ ' , with Protect Stack. If you set the modify, delete, or user level buttons in the Protect Stack dialog box, chances are that you don't want the user to be able to get , . to this box and make changes on his own. To prevent access to the dialog box, you can password-protect it. Click on the Set Password , ,: , button in the Protect Stack dialog box. This brings up another dialog - , j . , . box requesting you to type the password of your choosing twice (Figure 5-8). It asks for two entries of the password to make sure you don't J mistype it accidentally. Passwords are case insensitive, which means Enter new passuiord here: apteryH Uerify new passuiord here: apteryj^ None ^ ■ * OK^ ] 1 Cancel 11. Figure 5-8. You must enter a new password twice to make sure you type it correctly. All About Stacks 107 that HyperCard does not distinguish between uppercase and lowercase letters. Therefore, the passwords "Webster," "WEBSTER," and 'Veb- STer" are identical in HyperCard's eyes. You may change your pass- word as often as you like by clicking the Set Password button in the Protect Stack dialog box again. Once you click the password box's OK button, you will no longer be granted access to the Protect Stack dialog box unless you type in the password (Figure 5-9), IMPORTANT: DO NOT FORGET YOUR PASSWORD UNDER ANY CIRCUMSTANCES. IT IS THE ONLY KEY TO THE LOCK. EVEN BILL ATKINSON CANT HELP YOU RECOVER YOUR PASSWORD. STORE AN UNLOCKED COPY OF A VALUABLE STACK ON A FLOPPY DISK BEFORE PASSWORD-PROTECTING THE OMGINAL, LIMITING ACCESS TO THE STACK ' 'A, ' : HyperCard provides a way of preventing casual browsers from access- ing a stack you wish to keep private {although a network-oriented privacy setup will be available in a future release of HyperCard). Here's how it works. • * • In the Protect Stack dialog box is a check box labeled Private Access. When you check this setting, you don't immediately protect the current stack from access by others. This privacy level works only the first time you try to open the stack in a new HyperCard session (that is, after start-up from the Finder) , When opening the stack for the first time, the password request dialog box asks for the password [the same password you set to limit access to the Protect Stack dialog box). Once you type In the correct password, however, you will not be asked again the next time you open the stack during the session. HyperCard, in essence, remembers the last password you type into the password request dialog box and applies it to the EMvate Access system. Note that this does not apply to accessing the Protect Stack dialog box: That Is always password-protected if a password Is In effect. LUhat's the passmord? OK Figure 5-9. Protected stacks request a passux)rd before allowing access to the Protect Stack dialog box. 108 HyperCard's Authoring Environment The reasoning behind this password remembrance scheme is that once you have successfully accessed a protected stack, you won't want to be prompted for a password each time you Go Back to or need a quick browse through that stack. In that situation, the Private Access system would be more of an Impediment than a help. To try out the Private Access feature, click the Private Access checkbox and set a password. Quit HyperCard. Then restart Hyper- Card and try opening the stack. You'll be prompted for the password. Once you type It In, you'll be given free access to the stack uniH the next time you quit HyperCard. FURTHER PROTECTION HyperCard offers one more rather powerful means of protecting a stack, although it requires knowledge of HyperTalk programming to get It going. By way of HyperTalk scripts, a HyperCard author can intercept any or all menu commands that a user might invoke. By carefully filtering out menu commands, an author may allow users to add new cards but prevent them from deleting existing cards (Intercepting the Delete Card menu option). Similarly, the author may allow the printing of Individual cards but prevent printing the entire stack or a report of the stack's contents (Intercepting Print Stack and Print Report). • K We'U have more to say about how to protect stacks In this manner In Part Three. CHAPTER 6 All About Layers -"1 Perhaps the most difficult concept a HyperCard author must master is the layering of HyperCard elements. The problem may stem from the usual way we see layers In the real world: from the side, like strata in geological layers or the moist tiers of a seven-layer chocolate cake. In HyperCard, however, we see the layers not from the side, but from above, looking through the layers. A HyperCard browser, who knows nothing about authoring Hyper- Card stacks, is never conscious of the layering process that has gone into the design of the stacks he uses. But as a stack author, you must be intimately familiar with layering. We'll start by explaining the two layering worlds of HyperCard: object layers and background-and-card layers. ■ ■ I - .^u: - , . - ■ ; . . ' ' i' . i . - i , , . .,.»-"' " ■■■ • . ? . . : Object Layers | . ' 1 , Each HyperCard element— called an object— is applied in its own layer. If the object is transparent ("see- through"), then we can see through it to layers beneath it; If the object is opaque {solid) , like a famUiar-looking clickable button, then that opaque object obscures our view of objects directly beneath it aE the way down to "bedrock." One way to visualize HyperCard's object layers is to make believe that even the smallest HyperCard object Is drawn on a fuU-screen-size sheet of crystal clear plastic. (If you've been exposed to the preparation of 109 HyperCard's Authoring Environment advertising artwork or cartoon animation, think of each layer as an acetate sheet.) Each object you add to the stack— a button or text field- adds one more sheet to the top of the pile (Figure 6-1}. Whatever object you designate as opaque will be visible through all the layers; if the object covers only a tiny portion of the screen, the rest of the clear plastic sheet will let other opaque objects below it be seen. If you apply another opaque object atop the previous one, then the object lower in the pile will be hidden from view (Figure 6-2). Transparent objects may be harder to conceptualize, but fortunately their transparency is primarily for the benefit of the browser. The author can "see" where transparent objects are located while creating Product Catalog Item *: Oesch p ■Picture Layer 4-FiBld Layer ::::::::::i Button Layer What the Author Sees Figure 6-1. Each object resides in its own layer. Picture Layer Product Catalog Item Oeac Cost Product Catalog foD Item *: Description Cost: What the Browser Sees |<-Field Layer -Button Layer 1 -Button Layer 2 • What tiie Author Sees firs r:-..- : Product Catalog Item *: Description: Cost: What the Browser Sees Figure 6-2, What the browser sees. An opaque object in a layer closer to the viewer (the No button, above) obscures an object in a layer farther awayjrom the viewer (the OK button). •t ,.t : All About Layers 111 and modifying a stack. Nevertheless, a transparent object allows opaque objects beneath It to show through, even though the property of the transparent object- like a text field's ability to accept typed text- is on top. This brings up an important distinction between an object's visible properties and its action properties. As examples of action properties, text fields accept and display text; buttons react to the click of the mouse button when the cursor is on the button. These action properties are Independent of their visual properties. A button, for example, reacts to a mouse click whether It is transparent or opaque. If an opaque button is beneath a transparent button, the topmost button— the transparent one— is the one that recognizes the click of the mouse. It's not the number of layers atop a button that prevents It from recognizing a mouse click, it's whether any other object (transparent or opaque} lies between It and the cursor (the cursor is the topmost object without fail]. Therefore, a button could be situated near the bottom of a 50-layer card, and it will react to the click of the mouse button provided no other object is in its way; the button essentially looks upward through aU the clear plastic sheets to see the cursor. Background-and-Card Layers In addition to the principles of object layers Just discussed, a Hyper- Card author must also recognize the difference between objects In the background and card (foreground) domains. Everything that you assign to the background domain will be visible and active on every card of a homogeneous stack. In other words, graphics, text, buttons, and text fields that go into a background design appear to be copied onto every card you or the browser creates in that stack. We refer to objects assigned to the background domain as "background" objects, such as background buttons and background fields. You can, however, also assign graphics, text, buttons, and text fields to a specific card. These objects are assigned to the card domain. In keeping with the clear overlay paradigm established earlier, aU objects in the card domain rest on top of background objects (that is, closer to the browser's eye). You might call card objects "foreground" objects, but it's better to remember that they are part of a single card. Therefore, If you assign an opaque button to one card, it will be visible and active only on that one card. We refer to such objects as "card" objects: card buttons and card fields. As you'll learn In a later chapter, you can use HyperCard's layering abilities to your advantage to simplify card and stack design. As a hint of what's to come. Imagine you have assigned a background button to 112 HyperCard's Authoring Environment perform a task when the user clicks on it. It may be that you don't want ' : : ; . the user to access that button on a particular card— maybe you don't want to encourage the user to proceed to the next card in the stack from the last card. On the last card in the stack, you could assign an opaque card button that has no action written for It, The button's card-domain opacity covers up the background-domain button that brings up the 1 next card. Moreover, the empty script for the card-level button assures that HjrperCard won't do anything If the user unexpectedly clicks the mouse button with the cursor on that card button . The net result is that you don't have to worry about assigning individual "next card" buttons to every card but the last one; just place the button in the background ' and cover it up on cards that don't require the action. . ".-.•'";■ . *•' ■: ' What the Browser Sees " " " Nowwell take what we've learned about layering to see how the browser sees various pieces of the layering puzzle. In the next few chapters, we'll have more to say about the specific objects we'll be showing here. For now. study the layering construction. To demonstrate the effects of additional layers, we'll graphically show an exploded view of the layers as well as a head-on view as tf looking at the screen. We'll use the building of a simple name and address HyperCard stack as an example. %.? :!;..;•.• ;: v: : ..rifiti f: STARTING IN THE BACKGROUND PICTURE First we start with a background picture, the "bedrock" of any card. The . background picture is the lowest possible layer {Figure 6-3) . Here, we'll . • put the picture of a rolodex-tjpe card and a grey fill pattern around the i ■ : i Figure 6-3. The background graphics layer is the "bedrock" of what a viewer ] sees as a card. All About Layers 113 F^ure 6-4. You can add any kind of graphic to the background, including art that underlies a transparent button, Uke the Home button art added here. card. Since the card and grey fill pattern are on the background layer {indeed, they are the background, as you'll see later), they are actually aU on the same layer. We can add any kind of artistic element to the background (see chapters 12-16), Including art that simulates a button. Note that we're talking about the button art, not the actual button object. For the sake of demonstration, let's say that we want to add a custom piece of art that will serve as the art for a button that will take us back to the Home card. Using HjrperCard's painting tools (or perhaps by cutting and pasting art from another HjrperCard card, MacPaint document, or other Macintosh source), we can add a house painting to the background (Figure 6-4). This house is on the same layer as the rolodex-type card and grey fill pattern, because we are adding the art to the actual background picture. BACKGROUND BUTTON LAYERS Next we can add the background buttons that we want on every card (there is no prescribed order for adding background or card objects: They may be added or modified at any time, even after a stack has been used for some time). For this kind of stack, we'll just put two buttons that help us navigate to the previous and next cards in the stack, For these buttons, we'll use some special buttons that come with HyperCard. These buttons, called icon buttons, already have art attached to them and scripts that perform the actions we need. Following HyperCard design conventions, the button art for previous and next card actions are left- and right- facing buttons respectively. We copy and paste them into the bottom comers of the card (Figure 6-5J. You can create only one button at a time. When you create a button, it establishes itself in its own layer. Therefore, even though we're creating these two icon buttons ri^t after each other, the first one we 1 14 HyperCard's Authoring Environment , ■■- ' What the Author Sees What the Browser Sees Figure 6-5. Each object is its own layer, which is like a transparent acetate sheet laid atop the background. Here, two buttons are added to the card's background domain. - 'iii Ivik-j 'vi; «>;jj create is in one object layer below the second one. To the browser, \ ■ , however, these two buttons look like ordinary buttons that happen to - C appear on every card in this stack. BACKGROUND TEXT FIELD LAYERS Next we add a text field to the background to eventually hold the name and phone number (Figure 6-6). Although we're bunching all the information into one text field for simplicity of demonstration, we could ' ; also divide the information into multiple text fields. As you become more accustomed to designing HyperCard stacks, you'll be able to quickly determine whether many single-line fields or one or more multiple-line fields better suit your stack design. The text field layer is Background Picture Left Button Layer Right Button Layer Field Layer rr.: What the Author Sees What the Browser Sees Figure 6-6. AJield object layer is added here atop the buttons. As long as the fveld does not cover the buttons, the buttons will be visible to the viewer. All About Layers 115 the last of our background layers. This is the blank card that the browser will see when he calls for a new card from the Edit menu. In Chapter 2, we covered how text information typed into a back- ground text field "belongs" to the card in which it was typed, even though the field Is in a background layer. With each new card, the browser gets a new blank field with font and other attributes estab- lished when It was assigned to the background layer. The text becomes part of the card layer- a very special relationship between a back- ground object (text field) and a card-level object (the card itself) that we'll examine later. CARD LAYERS It is also possible to add graphics, text fields, and buttons to the card domain. They heap atop the object pile, but "belong" to the one card to which they are added. Let's see how that affects the name and address stack we've watched grow so far. Let's say we want to add a button to Tom's card. We'll later train that button to Jump to another stack that contains a map to Tom's house. This calls for a card button, since we have a map only for Tom's house, and it's not likely we'll add too many more maps for people in this name and address stack (if nearly everyone had a .map, it would be more efficient to add such a button to the background and cover it up on cards that don't need it). When we add the button, we must be careful to place It on the card so that it does not obscure the background buttons or backgroimd field {Figure 6-7). To the browser, the card looks like all the others in the Background Picture ■ Left Button Layer Right Button Layer Field Layer "I*- Card Picture What the Author Sees Whet the Browser Sees Figure 6-7. Ail cards have a card picture layer (the nearer heavy-outlined card above), which may or may not contain graphics. Object layers may also reside in thecarddomain, lifce the Map button above. No other card in the stack wUl fuive that button. 116 HyperCard's Authoring Environment stack, but with one extra button. The browser, unaware of the _ background and card layering, sees all buttons as if they were on one •,. ' level. We could go back at any time and modify a layer or add a layer as the application requires. If we wanted to add another background button, we would instruct HyperCard that we wish to work in the background. : HyperCard obliges by temporarily hiding all card- level objects. The new . button we add would go on top of the background domain, but beneath the card domain, no matter how many background objects we Insert (Figure 6^), Similarly, we can add graphics or objects to the card level. For Instance, if we had a small MacPaint sketch of Mary's face, we could paste it into her card. This graphic Is considered card-domain informa- tion, Just like the text typed into the text field blank on the card. Therefore, the graphic "belongs" to the card— it is part of the card object. Layers and Heterogeneous Stacks ' , ' We've come to know, now, that in a homogeneous stack, all the ■ ' background objects are in a sense grouped together and remain in view V' ■ at all times . A card and its objects are also grouped together. When you ■ • ' view a card, therefore, the card's information and objects essentially overlay the background. Flipping through a stack simply overlays each card's information atop the static background. TTie principles are the same in a heterogeneous stack, but the stack's "* ' ' multiple backgrounds throw a little twist into the stoiy. Recall that a Card DOMAIN Figure 6-8. When you insert an object to the background domain, it is added as a new layer closest to the viewer, but just behind the card graphics layer. Ali About Layers 117 homogeneous stack has one background. As you flip through the cards, that background never changes, even as the cycle of cards begins anew {that is, proceeding from the last card in the stack to the first card). In contrast, flipping through a heterogeneous stack will eventually lead you through the multiple backgrounds. A convenient way to organize a heterogeneous stack is to group together all cards that share the same background (Figure 6^). Therefore, if you have fifty cards with background A and 100 cards with background B, you can start at the first card of background A, proceed to the next card forty-nine times, and view only cards with that background. But if you are looking at the last card of background A and ask to view the next card, you will see the first card of the background B group. With regard to layering, you should remember that a background is the "bedrock" of a card. Therefore, elements of two distinct back- grounds will not interfere with one another. A background's art, buttons, and text fields are said to be "private" to that background: They are not shared with any other background. That means, therefore, that if you wish two backgrounds In a heterogeneous stack to have identical features in places— such as the next and previous card buttons— you must specifically design those buttons into each background. Don't expect a second background in the same HyperCard stack file to automatically inherit any attributes of the first one you designed. Fortunately, HyperCard does simplify manually borrowing objects from one background to another, as described In the next several chapters. Background Background "A" Figure 6-9. Cards created by the New Card menu item in a heterogeneous stack are automaticnlly grouped in such a way that all cards sharing the same background are contiguous in the stack. CHAPTER 7 All About Backgrounds We will be UMinNG discussion in this section to the background picture layer— the "bedrock" layer, as we've called It. Background buttons and fields will be covered in their respective chapters. In all our illustrations about backgrounds so far, we may have given the impression that every stack has some kind of graphical back- ground. It's true that most stacks do have such a background, but it is not a prerequisite that a stack have a graphical background to be an official stack. Every stack, of course, has a background picture layer. In its pristine form, a background picture layer is completely blank- white on the screen. If you ever design an entirely custom stack, this is where you will start building— a frightening thought, perhaps. Backgrounds and the Browser What the browser sees as graphics in the background of a card is nothing more than a careful arrangement of dark spots on the white background. Just as a newspaper photo upon close inspection consists entirely of black ink dots on a white paper. The design that results is entirely up to the HyperCard stack author. As stack author, especially for stacks that will be used by others, your responsibility is to make backgrounds appealing and intuitive. When a browser encounters your background, its purpose should be obvious. 119 120 HyperCard 's Authoring Environment or should at least offer an obvious way for the browser to get help In some fashion. The background graphic is important. The browser will adopt a third- party stack initially for its information content; the degree of enjoyment that person derives from the stack, however, is much more dependent upon the design of the background. A stack with a well-designed background will have a much higher perceived value than the same stack with an amateurish or awkward background design. BACKGROUND STRATEGIES A common design theme running through most of the stack and card ideas provided on HyperCard's ideas disk is that a card background should be an on-screen metaphor for something in real life, like a note card, an appointment calendar page, or some other paper form. These may be fine ideas to start with, but don't let them influence you tnto thinking that this Is the only way to design a card background. Sometimes an entirely new way of representing a familiar form is more appropriate. Additionally, unchain your Imagination from the confines of traditional forms and explore new ways of using the Macintosh screen. As you see other Macintosh applications and screens, remember that it is a simple process to capture the art from a screen onto disk and paste It Into a background of a stack you design. You can also cut and paste sections of one HyperCard card background into another. As a result, you can achieve remarkably professional-looking card back- grounds even If you are not an accomplished artist. (A word of caution, however, if you plan to offer a stack you design for resale. Copyrighted background and icon Eirt may not be used as component parts of stacks for redistribution to others unless you obtain permission from the copyright holder. Personal use of such art, however, is a common practice among Macintosh users.) ' Blank Backgrounds Surprisingly, there are cases in which your HjrperCard stack design may prescribe a background picture that is completely blank (white). ' In fact, the stack may not even have any background fields or buttons, either. An example of such a creature might be a stack of one card whose content is a graphic chart, like the Periodic Table of Elements. There is ' only one periodic table, so there is no need to put the table's art Into the All About Backgrounds 12 1 background for additional cards to share. The art can be pasted, instead, into the card layer. Underneath the card layer, the background layer is blank. Another example, this time with a stack of many cards, might be a stack consisting of chp art. The art is pasted, card by card, into the card layer. If the art may extend to full screen size, you won't want any kind of decorative border in the background to run underneath the card's content. Therefore, it may be best to keep the background blank. In such a stack, there may still be background buttons and fields, but the bedrock background layer is empty. Background Info... ' ; ., At any time while in Authoring or Programming levels, you can see information about the background of the card you are viewing. Pull down the Objects menu and choose the Background Info... item. You will see a dialog box similar to the one you get for Stack Info (Figure 7- Background Name: Help Formal| Background IB: 2765 Background shared by 285 cards. Contains 1 background fields. Contains 0 background buttons. □ Can't delete background. Script... 1 r~ OK j Cancel | FJgfure 7- 1 . TTie Background Info dialog box tells you about the number of objects in this background, the number of cards, and the background name. An additional setting allows for a level of protection against or deletion. 1 22 HyperCard 's Authoring Environment Notice that the first item In the box is a blank for a name. You can assign any name you please to the background. For now, this may not seem particularly helpful. But when you begin programming in Hyper- Talk, object names (bacl^ounds, cards, fields, and buttons) wiU prove to be very practical. Therefore, it is not a bad idea to get in the habit of assigning names to objects you create. Other information about the backgroimd in this dialog box includes its unique id number and the number of cards, fields, and buttons assigned to this back^ound. You are also given the opportunity to protect backgrounds from modification or deletion in case you wish to protect only one background in a stack. This background status report will prove helpful in future design of HjrperCard stacks. Like stacks and other HyperCard objects, a background may have a script attached to it. You are free to inspect the script by clicking on the dialog box's Script... button. If there is a script there, look but don't touch until we've had a chance to acquaint you with the essentials of the HyperTalk language. CHAPTERS All About Cards As WE DID FOR THE BACKGROUND DISCUSSION IN THE LAST SECTION, OUR COVERAGE of cards in this section is restricted to the actual card picture layer, not to buttons and fields that may exist in this "foreground" layer. Card and Background Interaction An intriguing property of the card picture layer is that it is treinsparent. But the card layer is a layer just the same, and as such may be the recipient of graphical elements, Just like the background layer. What makes this relationship between background and card pictures so Interesting is that a stack designer can perform visual tricks by orchestrating the interaction between the two layers. For example, if a section of background art applies to all but a few cards, that section can be covered by different art in the card layer. Even if the background element art is surrounded by the white of the background, the card layer can cover it. But to do so, the author must paint a white patch on the card layer to match the background's white field. As you'll see in the discussion of painting tools, this might feel funny, because to your eye it appears as if you're painting with "nothing"— the paint blends with the background white. Another kind of interaction may involve overlaying a card layer pattern atop a background layer pattern. Again, we'll have more to say 123 HyperCard's Authoring Environment about patterns in our discussion of the painting tools, but look at Figures 8-1 and 8-2 to see how a card layer pattern interacts with a background map to create a striking day/night contrast. V -5 ■- FYgure 8- J . This voorld map is a background. Land areas are white, while ocean areas are filled with a dotted pattern. Figure 8-2. A card layer graphic consists oj a cross hatch pattern that complements tfie ocean pattern in the background. The result is black Jor the night oceans, and the Crosshatch pattern for night land areas. (Reproducedfrom Business Class, a stack published by Activision, Inc.) All About Cards 125 Card Properties We've said it before, but it bears repeating at this stage: The information you tjrpe into a text field "belongs to" the card In view at the time, even if the text field Is a background field. It's Just like the note card In the library card catalog. The spot on the card designated for the book's title Is determined by the placement of that blank In the background (that is, it is the same for all cards in the drawer), but a particular book's title is actually entered onto the card. Wherever that card goes, so goes the information tjrped onto it. To help hammer this point home, HyperCard automatically assigns numbers to cards in a stack. There are actually two numbering systems imposed on cards in a stack. CARD NUMBERS First of all, cards in a stack are recognized by their place in the stack. A card in a stack has a number relative to the start of the stack. That is, HyperCard counts cards, one by one, from the first card in the stack. If you know the precise location of a card relative to the beginning of the stack, you could issue a command in the message box like "Go to card 22." The problem with relying on this numbering system to locate a card (other than the first and last card in a stack) is that the number of a card can change during the life of a stack. For instance, if you delete card number 2, all the cards above that number slip down a number to fill the gap left by the card yanked from the number 2 slot. Even more hazardous to this numbering system is the way HyperCard adds a new card to a stack. Unless instructed otherwise, HyperCard slips a blank card after the card you're viewing, ready for you to fill out. If you're not at the last card in the stack, then the numbering system for cards above the new card will be off by one. Fortunately, HyperCard comes through with a much more reliable numbering system that works automatically for you each time you generate a new card In a stack. Immediately upon creation, a new card receives a unique identification number, csdled Its card id. A card maintains its card id virtually forever. No other card in that stack will ever again be given that id number, even after a card is deleted. Like the Jersey numbers of famous professional baseball and football players, a card's id nmnber is retired upon the card's deletion. 1 26 HyperCard's Atithoring Environment CARD NAMES A HyperCard author also has the option of assigning names to Individual cards. For most stacks, particularly homogeneous stacks that may grow to be quite large (name and address or daily calendar stacks, for instance) , naming cards won't be of much value. Card names will be important, however, if you start writing HypeiTalk scripts, especially in heterogeneous stacks. We'll see much more about card- naming In later chapters covering HyperTalk. Because a card is an object, you can obtain information about it by choosing Card Info... from the Objects menu. The dialog box that results is very much like ones we've already seen (Figure 8-3). It offers a blank for entry of a card name, followed by its sequence number in the stack and Its unique id number. Next the number of card domain fields and buttons assigned to that specific card are listed, as well as a protection setting for deleting an individual card. Cards, too, can have HyperTalk scripts, and the Script. . .button is the portal to the script dialog box. Selecting Cards , , . C ' There Is one special case in which the card terminology may seem to be confused with that of the background. It has to do with the Edit menu choices labeled Cut Card and Copy Card (Figure 8^). Card Name: Conuersion Factors] Card Number: 83 out of 285 Card ID: 40924 Contains 0 card fields. Contains 0 card buttons. □ Can't delete card. Script. OK ] I Cancel | F^ure 8-3. Card Info dialog box ' All About Cards 127 Undo 3gZ Cut rnnii cow Paste Picture Clear New Card Delete Card Cut Card Copy Card k Background jFT^rure S-4. Copy Cond and Cut Card menu choices When you make this menu choice, HyperCard cuts, or copies, the complete card you're viewing at that instant. By "complete card," we mean the background, all background objects, the card layer {with the Information stored in that card), and card objects. Both commands place this card into the Clipboard (Cut also removes it from the stack). Once the card is in the Clipboard, you can then go to another stack and paste this complete card into that stack. The moment you do that, however, the stack gains not only an additional card but an additional background. In other words. If you were to check the Stack Info dialog box before and after the paste, you will see that both the number of backgrounds and the number of cards has increased by one. This is a very handy feature for a very specific purpose: building heterogeneous stacks from homogeneous stacks. In fact, it points up a good strategy for developing heterogeneous stacks. Work first with the building blocks as separate stacks to prevent getting mixed up between multiple backgrounds in a developing stack. When the basic blocks are all set, then make one of the stacks the recipient of the other backgrounds. Go to each of the other stacks, copy a card, go to the target stack, and paste the complete card (card and background) into the target stack. Now you can connect the workings of the diverse 128 HyperCard's Authoring Environment backgrounds by establishing appropriate links with buttons (dis- cussed later). If you are interested only in selecting information stored in a card's text fields for copying and pasting elsewhere, use the standard Macin- tosh text editing tools, as you would in a word processing program. In other words, use the text pointer to select text, choose Copy from the Edit menu, go to the destination, place the text pointer in the desired location, and choose Paste from the Edit menu. Do not use Cut Card or Copy Card for this kind of operation. 4- ' ^ CHAPTER9 All About Fields Text fields are, by and large, the information holders of HyperCard cards. Except for stacks designed to hold different graphics Images on each card (as in a clip art stack), the practical value of a stack you create wUl flrst .be evaluated by the textual Information it stores for the browser. Fields vs. Graphic Text We should make one important distinction at this point: Text fields are not used when you wish to display fixed text in a card (or every card in the stack), as in a uniform card title. Text fields are predominantly of the fill-in-tfie-blank variety. When you wish cards in a stack to display fixed text, the most efficient way will be to make the text as part of the background picture layer. HyperCard's painting tools (chapters 12-16) provide a facility for typing text into these layers. If you type some text into the background graphics layer, that text will appear on every card. Just like the rest of the background graphic. A background text field, on the other hand, wiU show up blank with the creation of each new card in the stack. Therefore, this section refers strictly to the fill-ln-the- blank type of text entry. 129 130 HyperCard's Authoring Environment Accessing the Field Tool — - - To work with text fields, you must select the Field tool from the Tools palette. Here's how: 1. Make sure you are at the Authoring or Scripting user level. 2. Pull down the Tools menu. This action reveals the Tools palette (Figure 9-1), As you recall from our discussion in chapter 4, you may drag the pointer off the palette to "tear" it from the menubar, 3. 'Tear ofT the Tools palette. Place it anywhere on the screen. 4 . Click on the field tool icon In the upper right comer of the palette (Figure 9-2). Depending on the construction of the card you are viewing when selecting the Field tool, the card's appearance may change slightly, as the borders of all text fields become highlighted or, in the case of transparent fields, suddenly visible. 5. When you are finished with the Field tool, return to the Browse tool by clicking on its icon in the upper left comer of the palette. You may dispose of the Tools palette at any time by clicking on its close box (Figure 9-3). Unlike the HyperCard objects discussed so far tn this part of the book, fields have many more properties at the discretion of the stack author. We'll divide these properties mto layer, visual, font, and HyperTalk properties. H r — n 1 1 1- 1 1 o O A O a. Figure 9-1. The Tools palette Aa About Fields 131 Tools ■h o 1 1 1 1 1 1 1 1 o O A o Figure 9-2. The Field tool is in the upper right comer of the palette. i 1 1 1 L _ U p 1 1 o o A O £1 Figure 9-3. Close the palette by clicking the close box in the upper lefi comer. Field Layer Properties ''"^^^ ' " We've already covered the difference between background and card fields with respect to the way HyperCard applies Individual layers to each object. The nature of most HjqjerCard stacks calls for practically all fields to be background fields: They are shared with all cards in a stack, but instances of card fields are easy to dream up. For example, if one card in a stack Is a kind of reference card, perhaps with tabular data to which other cards tn the stack frequently refer, you may create that card's table art and infonnatlon-containing text fields in the card layer. This card layer essentially masks the stack's primary background. By putting the text fields in the card domain, while other cards in the stack use background fields, the tabular data fields won't interfere with the background field information. 132 HyperCard's Authoring Environment Another case might utilize the layering properties that let you place a card domain object directly atop a background domain object. Therefore, there may be one card whose text fields you would Uke to display In a font or font style (boldface, perhaps) dlffisrent from the rest of the cards In the stack. To accomplish this, you would add a card field to that card, and place It precisely atop the corresponding background field. By adjusting the font information (see below), you will assure that the browser will see text in that spot In a different style than the other cards. FIELD ORDER ' Since each text field on a card Is Its own layer (remember, like the clear acetate sheets), fields assume an order based on the way the layers stack atop one another. The order of fields can be quite important to the browser, although he doesn't realize that field order is due to layering. It becomes Important when the browser is pressing the Tab key to advance the text cursor fi-om one field to the next. A press of the Tab key tells HyperCard to cany out two main tasks. The first task is to save to disk whatever new information was typed into the field where the text insertion pointer is now located. The second task is to move the text Insertion pointer to the field next In line, that is, the field In the next layer closer to the browser's eye. Let's explain. When you create a new stack and begin creating new background fields for that stack, HyperCard assumes that the first field layer you lay down is the "first field. " The field in the next layer (building out, away from the background picture layer) becomes the "second field," and so on. When the browser uses that stack, he presses the Tab key to - advance the text cursor from the first field, to the second field, and so on, until he reaches the frontmost field In the card. TTie next press of the Tab key starts the cycle all over again, starting with the first field, on the very bottom of the layers . ., . . _ .. A FIELD EXPERIMENT , ? jil , . We're going to experiment with this field ordering in the next couple of - pages. To really see how this works, let's make a new stack fi-om one of the stacks provided with HyperCard that has several text fields on it, We'll make a temporary new stack from the weekly appointment book background in the Datebook stack rather than mess up the one that ; , came with HyperCard. Let's make the new stack first: . ' 1. From the HyperCard Home card, click on the Weekly icon r'.>,r..,.-^ (Figures^). , , Aa About Fields 133 Figure 9-4. Clicking the appointment book icon in the Home cxird. 2 . With the appointment book on the screen, choose New Stack, . . from the File menu, ■ 3. At the standard file dialog box prompt, type the name "Field Explorer" as the new stack's name, and press Return. Now we're ready to experiment with the text fields on the card. As you move the screen cursor overvarious parts of the card, you'll notice that whenever it is atop what looks to be text field, the Browse tool changes to the I-beam text cvirsor. 1. Click the I-Beam cursor at the upper left comer of the top left text field {Figure 9-5). 2. Press the Tab key once. Because of the way the text fields were laid out by the author of this stack, the text pointer advances to the next logical field, the one for the second day of the week. 3. Press the Tab key a few more times. As you do so, watch the progression of the text pointer from one day to the next. ^ - The progression from day to day was no accident. The author planned it that way because it was what the browser would expect. Now, you may think that this places an exorbitant burden on the author to make sure the design of text fields is nailed down well in advance of actually building a stack. In practice, a card design evolves through trial and error. The author may sketch out on paper the basic 1 34 HyperCard's Authoring E^nvironment Figure 9-5. Clicking the I-Beam cursor at the top left comer of the Monday field ' sets the text insertion pointer JUxshing. function of a card and then start assembling the pieces on a real stack, After working with the stack for a while, the author can see what "works" and what doesn't. MODIFYING FIELD ORDER What If the author discovers that he must Insert a text field to the card in such a way that the browser tabs to it between the fields originally designated as the first and second fields? Does he have to start from scratch, assembling the layers in the new order? . c .fk" Fortunately not. HyperCard gives you the abUily to modify the order of text fields (and button objects) within either the background or card domains. The commands that accomplish this, found in the Objects menu, are called Move Closer and Move Farther. Let's see how they work, ' ' We'll use our Field Explorer stack to experiment with manipulating ^ field layers. AU About Fields 135 1 . With the Field Explorer stack In view, choose Background from the Edit menu. The menubar displays short diagonal marks along its top and bottom edges, indicating that you are in the background editing mode. 2. Pull down the Tools menu and choose the Field tool in the palette's upper right comer. Outlines of the text fields on the card become visible. 3. Click once anywhere within the first text field, that is, the field that contains appointments for Monday. This actions selects the field. Its outline turns into what Is called the marquee or the marching ants, giving you visual feedback that this field is, indeed, selected and that your next action wiU affect this field only. 4. Pull down the Objects menu and choose Move Closer (or bjrpass the menu entirely and press the keyboard shortcut, Command- +, the +/= key). Nothing much happens on the screen when you do this, but there has indeed been a change In the order of the text fields. 5. Pull down the Tool menu and choose the Browse tool. The outlines to the fields disappear, and the menubar returns to its normal appearance, Indicating that you have also come out of background editing mode. Before we look at the results of this maneuver on the screen, let's examine what happened schematically. When we started, the six text field layers in this stack were in the order shown in Figure 9-6. Then Field 1 Field 4 Field 2 Field 5 Field 3 Field 6 Figure 9-6. The ordinal order of the six Jields allows orderly advancement through the week by pressing the Tab key. 136 HyperCard's Authoring Environment we selected the bottom field layer and moved it closer by one layer. This means that the field originally in the number 2 slot has now become number 1 ; the field originally in the number 1 slot has now become number 2 (Figure 9-7). The order of fields 3 throu^ 6 have been unaffected by our single-layer shift. Let's see if it worked: 1 . Click the I-Beam cursor at the upper lefl; comer of the Tuesday text field. ^ . , - This field, if our calculations are correct, should be the first field In the order of the six. 2. Press the Tab key once. ■ ' ' > The text pointer now advances not to Wednesday but to the field considered number 2, the Monday field. ^ ( 3. Press the Tab key once more. Now the pointer advances to field number 3, Wednesday, Subsequent presses of the Tab key advance the pointer to the appropriate days until it is time to start the cycle over again. At that time, the pointer advances to the first field— Tuesday, in our mixed-up week of fields. The action of the Move Closer and Move Farther commands, then, works on one selected layer at a time, and shifts that layer in the desired direction one layer at a time. "Closer" means closer to the eye of the viewer; "farther" means farther away from the viewer's eye. You should also be aware that when you select a text field layer, for instance, and start moving it in one direction, you are moving it not only with respect to other text field layers, but to button layers as well. Let's examine this more closely. " > > ' . Field 2 Field 1 Field 3 Field 4 Field 5 Field 6 Fig lire 9-7. Afier bringing thejirst field closer by one layer, the Tuesday fieM ts now the first in field order. Tab key cursor advancement fi)llows the new order. Tuesday, Monday, Wednesday, Thursday, Friday, Saturday/ Sunday. Ail About Fields 137 Recall that in the background domain, you can have many text field and button layers (one layer per object) sitting above the actual background graphic layer (Figure 6-7). If you had created the layers in the following order, picture field A button 1 button 2 field B HyperCard sees the background picture and four object layers in that order. The Move Closer and Move Farther commands treat all object layers within a domain as equals. Therefore, if you wish to change the order of the text fields so that f^eld B is the "first" field for this card, you would have to select that field and issue the Move Farther command three times. At each step of this process, the order would look like this: Move Farther (11 Move Farther j2) Move Farther (3) picture picture picture fields - button 1 ''"^ ^ ' button 1 button 2 button 2 button 2 It Is only after the third issuance of the Move Farther command that field B actually moved ahead of field A as far as the browser would notice with the way the text pointer responds to the press of the Tab key. During the first two commands, the field B layer was working its way through two button layers. What you must observe as an author, therefore, is how object layers are laid out in case you need to change their order. On a card that has a couple dozen objects, it may take many presses of Command- +, for example, to move an object to the layer closest to the viewer's eye. In our discussion a bit later about buttons, we'll set up a multilayer system of easily visible overlapping objects and shift them freely from layer to layer to demonstrate the effect. Moving text field layers with Move Closer and Move Farther works only vrithin the confines of the domain in which the field was originally created. In other words, if you create a background field, the Move Closer command will not bring that field into the card-level domain. The card picture layer acts as a kind of barrier to shifting layers around. Layers created In the background cannot come any closer than one layer immediately below the card picture layer. Conversely, card object layers cannot be pushed away from the viewer any further than one layer immediately above the card picture layer. There are facilities for field A button 1 field A field B Held B field A 1 38 HyperCard's Authoring Environment cutting and pasting fields from one domain to the other, as we'll see in a moment. Field Visual Properties ■ ' _ Text fields give the author many options for their appearance on cards. These choices are made by clicking various buttons on the Field Info dialog box (Figure 9-8). You can choose from one of five field styles: transparent, opaque, rectangle, shadow, and scrolling. Moreover, you can turn on any of the following three options: lock text, show lines, and wide margins. Text fields. In general, are rectangular areas on the screen. Except for scrolling fields , the only limit to the number of lines a field may display ' - on the screen is the size of the HyperCard screen. The same goes for the I width of a text field. A text field could , if your card design dictated, fill the entire screen. The actual number of text lines a field will display on the screen at any one time is also dependent upon the font size and line spacing you select for the field (see below). Text fields may be created fresh (discussed below) or may be copied and pasted from other cards In other stacks. Text fields you copy and Date Field Name: Bkgnd field number: 5 Bkgnd field ID: 19 □ Lock TeHt El Shoui Lines □ lllide Margins Style: „ (S) transparent O opaque O rectangle O shadoLu O scrolling Font.. Script. ^3 Cancel Figure 9-8. The Field Info dialog box AU About Fields 139 paste from other sources may be resized to suit the needs of the stack you create. Visual attributes of any field are set by various buttons In the Field Info. . . dialog box (Figure 9^) , which you can see by first selecting a field (remember, you must choose the Field tool from the Tools palette first) and choosing Field Info... from the Objects menu. As a shortcut, you may also double-click on a field with the Field tool selected to see the dialog box— a procedure you will quickly come to follow after designing a few stacks. c-'-i'v FIVE FIELD STYLES Of the five field styles (transparent, opaque, rectangle, shadow, and scrolling), you may choose only one at a time. A transparent field appears Invisible to the browser. That is. there is no discernible outline to the field area on the screen. The only clue HyperCard provides to the browser that a transparent field exists is that the Browse tool changes to the 1-Beam when it Is in the text field's territory. You would specify a transparent text field primarily when something in the background graphics layer gives a visual clue to the browser that a text field sits ready to receive or display textual Information. For example, the background design may call for a fancy border around the text entiy area. The border would be executed in the background graphics layer. The transparent text field would overlay the graphics area (Figure 9-9). To the browser, the combination looks like a fancy text entry box. Background Picture I.I . I'lV ■ 1 ■ 1, ■v 1 ■ 1 1 1 ■: '11 □ What you see Transparent Background Field Figure 9-9. A transparent background text Jleld combined with an intricate background picture creates an interesting entry Jleld for the user. 140 HyperCard's Authoring E^virormient You should be careful in your use of the transparent field atop a graphically rich background layer. The rectangle of the field is, as Its •■>>'h i name implies, completely transparent, revealing all graphics beneath it. If the background coming through the field is too "busy," you run the risk of making the text hard for the browser to read (Figure 9-10). : i . ,■ If you have a rich bacli^ound and want the text field to be a plain white area without any border imposed on it, then choose an opaque field style from the Field Info dialog box. An opaque field overlays the background graphics layer with a white rectangular region. You are assured that text typed into the field will be readable, regardless of the visual interference coming from the background layer (Figure 9-11). H^id i« hard to rdlliiiMi^i^^liii ' Figure 9-10. When cqiplying transparent Jlelds, be carejul that text is readable atop the background or surrounding graphics. Illll TeKt in this opaque field is easy to read against a busy !!%! background. Figure 9-11. An opaque Jield obscures a busy background picture, molring text very readable. All About Fields 141 A veiy common field style is the rectangle. With this choice, you get an opaque rectangle surrounded by a single black border line. The rectangle style will be most familiar to those browsers who have experience working with Macintosh database programs, which often display entry fields as black-bordered rectangles, lypically, a rectangle field will be accompanied by background art that contains text titles of the kind of information that should go into the rectangular text area (Figure 9-12). The shadow style presents an opaque rectangle drawn with a black border and a graphic technique called the drop shadow (Figure 9-13). The drop shadow adds a feeling of depth to an ordinary text box. Name: B. Ebson Street : 500 Wingra Drive City: Madison State ZIP: Telephone : Figure 9-12. Rectangle Jxelds are frequently used to designate text entry areas on a form. f Figure 5-23 | Monterey Cypress Cupressa macrocarpa Large groves may be foimd at the Point Lobos Reserve, about 0 Figure 9-13. Shadaw^pelds, like the one with the figure number above right, are opaque and appear with.adrop shadow around their borders. They can be used for dramatic effects when needed. Scrolling fields, bottom right, may be used where text may run longer than allotted space on a card. 142 HyperCard's Authoring Enviromnent Experienced Macintosh screen designers encourage sparing use of drop shadow devices, since the technique Is often overused. That's good advice. In the HyperCard environment, shadow- style text boxes are perhaps best used in those designs that call for a text field to be hidden (that is. completely invisible, including the content of the field) until the browser clicks on a button. The shadow text field then appears, providing some additional information or assistance. A click on another button or on the text field itself causes the shadow field to once again disappear (Figure 9-14). Its three-dimensionality works well in presenting this kind of overlapping note metaphor. The last field style, the scrolling field, extends the card boundaries for entering and storing text. A scrolling field (Figure 9-13) automatically display savert leal scrollbar to help the browser view text running below the visual limit of the field. TEXT LOCKS, LINES, AND MARGINS Now onto the three other visual properties that can apply to any field style. The first, Lock Text, is a valuable option for the HyperCard author who intends to present read only textual information in stacks for others to use. When you specify that a field's text is to be locked, the browser cannot accidentally change the text, even if he knows enough to change his user level to Typing or higher. When the screen pointer comes into a locked field, the Browse tool does not change into the 1- Beam cursor. Nor can the browser tab into a locked field from an unlocked one. This feature makes HyperCard a good way to safely distribute information to colleagues without fear of them accidentally erasing Information stored on cards. If you design a stack with locked fields, you'll have to create the stack first with unlocked fields. Only after you enter the information into the cards should you then lock the a stack Hel p ^HyperCard Help Figure 9-14. Use shadow fields for notes that are normaily hidden fiom view. The drop shadow effect looks like an overlay atop the rest of the ctu-d layers. AH About Fields 143 fields. Fortunately, by placing the field in the background, you can lock one background field and lock the text in that field for all the cards in the stack. Another option is the Show Lines property. When you engage this option. HyperCard displays a dotted line across the full width of the field (although not in scrolling fields). If you size the field for multiple lines. HyperCard shows as many dotted lines as the space allows. The vertical distance between the lines corresponds to the font size and line spacing specified in the field's Font dialog box (below). The ability to show dotted lines in fields is a most useful card design element. For one thing, it eliminates the need for you to emulate dotted lines m the background graphics layer- not an easy task when trying to align graphic lines with text in an overlaying text field. More importantly, if the user of your stack prefers a larger font size for greater readability. HyperCard automatically adjusts the field's dotted lines with the font. If the lines had been graphically done in the background the user would be confronted with the substantial task of digging into the painting tools and carefully aligning more widely spaced dotted lines to the larger line spacing. Showing lines also gives more solidity to b-ansparent and opaque fields, which, by themselves, are virtually amorphous to both browser and author. The last design choice is Wide Margins. With this option, you have a measure of control over the formatting of text in a text field. Depending on the design of your card and the size of your text fields, it may be desirable to have more white space between the characters in the field and the edges of the field. The Wide Margin selection increases the width of both left and right margins by approximately one character and the top margin by about one-half line. Generally speaking, very large text fields often look better with wide margins, but this is not a steadfast rule. As you design your cards, try your fields with both standard and wide margins. Then judge for yourself which does the best Job. Font Properties If you've done any word processing on the Macintosh, you've probably become quite familiar with the ability to change typefaces ("fonts" in the Macintosh lexicon), character sizes, and character styles at wiU HyperCard text fields give you most of that power with one important exception. Unlike the word processing environment, the font, font size and font style you select for a text field applies to the entire field. You cannot, therefore, adjust one word in a field to be boldface, while the rest of the text in that field is in plain text. Similarly, when you specify 144 HyperCard's Authoring Environment Style Chkdgo □ Bold Courier □ itaric Geneua □ Underline Heluetica □ Outline Monaco □ Shadoup New Vork □ Condense Times □ EKtend Rlign ® Left O Center O Right [cancel Line Height Sample Figure 9-15. The Pont dtalog box, accessible via the Field Irifo dialog box. that a text field is to be the 1 2-polnt Times font, the entire field is in that font and size. Font attributes are adjusted by controls in the Font dialog box. which is accessible via the Field Info dialog box (Figure 9-15) . These are no different from most word processing program font selection dialogs, although you may be used to having many of these choices available as menu options. Two attributes— alignment and Une height— should be explained In some detail. Text alignment— left, center, right- pertains to the alignment of text in the selected text field. The default setting (the setting HyperCard automatically gives to a new field unless you teU it otherwise) is left alignment. This is how most word processing text is aligned. How you align text In a HyperCard text field will depend largely on where you position the field on the screen. For example, if the design calls for a text field comprising the title field for a card to be placed along the right edge of the screen, then it may make excellent sense to specify right-aligned text. One attribute you may not be accustomed to seeing— line height- is at times a crucial measure when designing your HyperCard cards. The measure, analogous to leading in the typesetting world, is the distance in points (1 point, or 1/ 72 inch) between baselines of text (Figure 9- 16). HyperCard offers default line spacing that may be too large when you are trying to squeeze many lines of text into a small area on the All About Fields 145 i ■■ ■■ ■ ■■ ■■■ ■■ ■■■ S" s : : : -s- ■ ■■■■■■ a i Jmm^^m' ".."S*.!. S.." ■„." BASELINE ~ . Leadi nq ASCENDER — ■1 "B ■ ■■ ■■■■■■■■I ■ ■ ■ i i ■ ■ ■■■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■■■■ ■ ■ 8 ■■■ ■ Hh hhh hhh m n, X- heigtil font size DESCENDER c Figure 9-16. Font size is measured in points (1 point =1/72 inch) between ascender and descender: leading is measured between baselines of adjacent lines. . ; - • .. -.■>:'■ - 1 . .• screen. When that happens, you can adjust the line spacing to a smaller size. A typical closely spaced setting is two points larger than the font size. When experimenting with line spacing and font sizes, be sure to test combinations on actual text, especially on letters that have descenders (like j, y, and gl to assure good readability. FONTS AND THE SYSTEM ' . • If you are planning to distribute a stack to other Macintosh owners, be aware of an important factor that may limit the variety of fonts you incorporate Into the stack. Even though your System File may contain many elaborate fonts, the System File of the users of your stack must also contain those same fonts for their text fields to look just like yours. For example, if you like the LaserWriter font called Garamond and design text fields in a stack around this font, other users without this font installed on their system will get another font in its place— perhaps New York. The results may be artistically disastrous. There are two ways to prepare for this eventuality. The simplest is to design your text fields around the standard fonts In the System included with HyperCard. The list is as follows: Font Size Font Name 9 10 12 14 18 Chicago • Courier • • Geneva • • • • Helvetica Monaco • New York • * 9 • Times • • • 146 HyperCard's Authoring Environment Just because these fonts are included in the HyperCard System FUe doesn't mean that everyone will have all fonts in all sizes in their system. This is especially true if a user adds HyperCard to an existing hard disk. If your text fields call for a font not in a user's System File, the Macintosh win automatically substitute an existing font. Similarly, If your field specifies a font size not Installed In a user's System File, the Macintosh will scale the font to that size. Either way, the results wlU not be what you expected. One way to assure that every user of your stack will have the fonts you specify is to use a small font set called system fonts: Geneva-9 and - 12, Monaco-9, and Chicago- 12. No one can remove these fonts from the System File with the Font/ DA Mover, because the Macintosh needs them for the Desktop. It may be cramping your style to very few fonts and sizes, but you are assured that this lowest common denominator of fonts is in every Macintosh. FONTS AND THE STACK . :k . ■ A second method to obviate this font concern is to include the desired font In your application. This technique, not for beginners, requires the aid of a utility program called a resource editor. One such program, ResEdit, Is commonly available from Macintosh user groups and on- , 1 line bulletin boards. But before you get too many ideas about attaching fonts to your , . . , stacks for distilbutlon, you should be aware of copyrights that protect most fonts. The copyrights prohibit your distributing the fonts with your HyperCard stacks without permission from the copyright owner. r; ,; ;. Technically speaking, if you wished to make sure an Apple font, such as Venice, were available on your distributed stacks, you would need , permission from Apple Computer. Therefore, unless you desi^ your own font for your stacks, the attachment of a font to a stack is probably t-j I not a good idea. ; 1 Everything we've been saying about fonts applies only to text fields that hold textual information. As a stack author, you may use any font you wish when placing text in the background or card graphics layers. When you use the appropriate painting tool (described In chapters 12- 16). HjrperCard is not placing the text into a text field, but Is instead laying down a series of black spots on the white or transparent layer, The ultimate user of the stack does not need that font installed In his System File to see the font you painted on the graphics layer. So feel free to choose from a variety of fonts in designing fixed backgrounds. AlZ About Fields 147 FONT TECHNIQUES AND SHORTCUTS Before finishing our discussion about font properties of text fields, we'd like to share a technique you may find useful in designing cards that stand out from the ordinary. The effect we're after is white text field lettering on a black background— reverse lettering, as it's known in printing circles. Although we haven't yet gotten to the painting tools, Just watch for now as we create the illusion of a black text field showing white characters. To accomplish this feat, first paint a black rectangle in the back- ground graphics layer where you want the text field to be on the card. Then create a transparent text field atop the black rectangle. The field may be either a background or card field, but you'll probably want it to be a background field so that It shows up on all cards in the stack. With the Field tool selected on the Tools palette, double click on the text field. At the resulting Field Info dialog box, click on the Font... button. No matter what font you specify for the field (Chicago works very weU). also click on the Outline check box (Figure 9-17) and then OK. Now, when you type into the text field, all characters will look white on the black background (Figure 9-18). Finally, here's a useful shortcut whenever you are in the Font dialog box of a field. You can double-click on a couple places to both make a selection and do the same as clicking on the OK button. For example. If you change the font from Geneva- 12 to Geneva- 10, you can simply Style □ Bold □ Italic □ Underline lEI Outline □ Shadoui □ Condense □ EKtend Rlign ® Left O Center O Right Cairo Chicago Courier Geneua Heluetica Monaco Mos Eisley Neil! Vork Symbol Times 1^ Line Height 16 F^ure 9-1 7. The Outline check box in the Font dialog box 148 HyperCard 's Authoring Environment Outlined Tent Rtop a Black Background Graphic L a ye r Figure 9-18. Outline characters on a black background look reversed. double-click on the 10 In the hst of font sizes inside the Font dialog box. That action wiU both select the 1 0- point font and close the dialog box. This double-click shortcut works when selecting a font or font size. A double- click on the selection is all you need to select and return to regular display. ... ,■>■:' "^v . . ? ^ - HyperTalk Properties It's really too early in this book to get deeply involved with Hj^erTalk. But we think it is important at this stage to explain the importance of assigning names to text fields. In the Field Info dialog box, the first entry is a small text box into which you may type a name for that field . If the field is a background field, the field name applies to the field regardless of the card currently showing on the screen. In fact, the field would be referred to as field so-and-so ■ of card thus-and-such. In a real stack, a background field named "State" would be visible on all cards in the stack. Information typed into that field on a card whose id number is 20 would be referenced by the [ ' information in "field 'State' of card id 20 . " Information in the same field ; on a card whose id is 4 1 would be referenced as being in "field 'State' i; of card id 41." HyperTalk scripts often retrieve and send information to and from text fields on cards. When you begin writing HyperTalk scripts, you will .. find it much easier to reference information in fields by a readily ; V identifiable name rather than by a field number. Therefore, get into the ' ' habit early of assigning names to text fields on your cards. One other comment about fields and H3T}erTalk. When a text field is locked, the screen cursor does not change from its Browse tool cursor. This means that you can essentially turn a text field into a button that performs some action when you click the mouse button with the cursor in the text field. We'll see how to do this in a later chapter, but you may Aa About Fields 149 want to keep this in the back of your mind as you begin dreaming up HyperCard card designs. Creating New Text Fields HyperCard provides two distinctly different ways to create a new field. The steps Involved In each method are quite simple. The trickiest part is remembering to place the new field In the correct domain: back- ground or card. Most of the time you use HyperCard, you are In the card domain, yet most of the fields you will put Into a card design are background fields. It is easy to forget to choose Background from the Edit menu (or press Command-B) before planting the field in the stack. To create a text field the easiest way, follow these steps: 1 . Since this is an authoring task, be sure you are In either the Authoring or Scripting user level. 2. Select the desired domain: background or card. 3. Pull down the Objects menu and choose New Field (Figure 9- 19). A five-line text field appears in the center of the screen. The marching ants Indicate the field is selected and that HyperCard has automatically selected the field tool. Objects Button Info... Field Info... Card Info... Bkgnd Info... Stack Info... Bring Closer Send Farther Nem Button ■SBoimnB Nem Backgroun< Figure 9-19. The New Field choice in the Objects menu 150 HyperCard's Authoring Environment The second field-creation method is a little longer but may be preferred by some HyperCard authors. Here are the steps: 1 . Pull down the Tools menu and select the Field tool, 2. Hold down the Command key. When you do this, the cursor changes to a "plus" sign. This is like a drawing cursor. . 3. Position the cursor at the upper left comer of the location on the . : screen where the field is to appear. 4. Click and slowly drag the pointer to the right and down (Figure 9-20). As you do, the outline of the field rectangle shows you the extent of the rectangle you are dragging. 5. When the field is the desired size, release both the mouse button and the Command key. • ■ Regardless of the method you use, HjrperCard creates the default style of text field, which is transparent, with no lines showing and with narrow margins. The default font is Geneva- 1 2. If those properties are acceptable, you can choose the Browse tool in the Tools menu (which also automatically brings you out of background editing mode, if you're there to start) and begin entering text into the field. Start here i_ Drag to Here Figure 9-20. Clickir^g and dragging on a selected Jield lets you resize it to suit your needs. The dotted text baselines show you how many text lines UJfH be available at the chosen font size. All About Fields 151 Customizing Field Properties More than likely, however, you will want to adjust the location, size, visual properties, font, and perhaps script for the field. In a moment, you'll see how to "clone" the field if you wish to add more fields of the same type to the card. Before you do your cloning, however, it is advisable to set all the properties. That way, they'O all be set in future clones, so you can deal simply with the fields' locations and names. If you clone the fields first, you'll have to adjust the visual and /or font properties field by field. We should emphasize that you are free to make any adjustments to fields at any time, even after information has been typed into them. For example, if you use a stack for a while and discover that a field should be in a larger font size and not quite as long, you may edit that background field for those attributes. The information typed into the field In the stack's cards will not be damaged. The next time you look at the previously entered cards, your old text will have the new attributes you assigned in the editing process. To change any attributes other than size and location, you'll need the Field Info dialog box. With the field selected, choose Field Info from the Objects menu. Alternatively, you can double-click on the object. You may then make any adjustments, as described earlier. MOVING AND RESIZING FIELDS " .i . - Changing the location and size of a text field will be familiar processes to anyone with experience in object-oriented graphics programs, such as MacDraw, Cricket Draw, and the object layer of SuperPalnt. Even if this is new to you, it won't be difficult to understand. Before you can edit a field in any way, you must first select the Field tool. Selecting this tool makes aU fields visible (except those that have been "hidden" by way of a HyperTalk command in a script or in the Message Box). Even transparent fields, which are essentially invisible when you view a card as a browser, are visible when the Field tool is selected. You see both an outline of the field and dotted lines represent- ing base lines for text (to let you know how many lines will be visible in the current font and font size). If you are adjusting a brand-new field, the field is already selected for you. To move a field on the screen, place the cursor in the center of the rectangle, hold down the mouse button, and drag the rectangle. The field follows the pointer as you drag it around the card. Release the mouse button when the field is in the desired position. 1 52 HyperCard's Authoring Environment To resize a field, place the cursor on one of the field's four comers. The comer you choose depends on the direction In which you wish to stretch or reduce the field's dimensions. E^eclse dragging and placement of objects on the screen is an acquired skill. Some users adapt to it quickly, while others need considerable practice. As an aid for all users, HyperCard lets you constrain (limit) the motion at any one time either vertically or horizontally on the screen. Even an experienced artist finds constrain- ing to be a useful shortcut when an object is properly aligned in one axis and needs minor adjustment in the other: Constraining the motion prevents the correctly aligned axis from getting out of alignment. You constrain the direction of an object drag by holding down the Shift key prior to clicking and dragging the mouse button. With the Shift key down, HyperCard watches the direction you drag the object. If you start dragging it to the left or right, HyperCard constrains movement to those two directions only. No matter how you move the cursor from top to bottom, the obj ect will move only to the left and right. Conversely, If you hold down the Shift constrain key and make your first dragging movement up or down, all motion of the obJ ect will be in those two directions only. Constraining also works for resizing fields. For example, if you hold down the Shift key and drag the bottom right comer of a field first to the right, you will be constrained to left and right motion only. A good strategy in resizing fields Is to first size its vertical dimension accu- rately, pajdng close attention to how Its lines of text will display. Once the vertical dimension is correct, constrain resizing motion to the horizontal, dragging the field to the desired width without harming the carefully adjusted height set earlier. Cloning Fields on the Same Card Chances are that if your card design has more than one field, the font and visual properties will be identical— at least good taste usually dictates this idea. Exceptions exist, of course. For example, if you have text fields in a card that are preflUed-out for the browser (and perhaps cannot be adjusted by the browser), they may be opaque rectangles without borders; fields in which the browser is encouraged to enter information may then be bordered rectangles. Still, the font and font size will probably be the same. To simplify the creation of multiple fields of the same style on a card, you can readily clone— "peel ofT if you will— copies based on the first field you create. Let's try it. All About Fields 153 1 . Pull down the Go menu and choose Home to return to the Home card. 2. Pull down the File menu and choose New Stack... 3. At the standard file dialog box prompt, type Clone Home as the name of the new stack, and click OK (or press Return). This creates a new stack based on the card design of the Home card. 4. Pull down the Edit menu and choose Edit Background, or type Coramand-B. The foreground art of the card disappears temporarily as we see the blank background graphics layer, one background field, and two background buttons. 5. Tear off the Tools palette and place it in a lower comer. 6. Choose the Field tool on the Tools palette. 7 . Double-click on the background field that was on the card when you created the new stack. Cheinge the field style from transpar- ent to rectangle, and click the Show Lines checkbox. The Field Info dialog box shows this field to be background field number 1. 8. Click the OK button in the Field Info dialog box. 9. Choose New Field from the Objects menu, ■ , 10. Double-click on this new field. f> - ' - rv.-: The Field Info dialog box shows that the new field we Just created is background field number 2, which puts it in a layer somewhere closer to our eye than field number 1 . 1 1 . Click the Shadow style button and then click OK to close the dialog box. c ^ii . ; 1 2 . Hold down the Option key (the cloning key) , then click and drag the new field we Just created (field number 2) to an area under field number 2. Release the mouse button (Figure 9-21). A copy of the field traces the motion of the cursor, leaving the original field in place. 13. Double-click on the field you Just cloned. The Field Info box shows this field to be field number 3, which is in a layer one level closer to you than field number 2. The box also shows that the shadow style is in force for this new field. 154 HyperCard 's Authojing Environment > ^ < File Edit 60 Tools Objects Ftgure 9-21 . Cloning afield makes an exact duplicate of the original Cbme by Liis?! holding down the Option key, clicking on the original, and dragging the copy. If you wish to add another field with the s£ime attributes, you can clone either field number 2 or field number 3, In practice, the most convenient method Is usually to clone the most recent field— number 3 tn this case. : COLUMNS OF FIELDS Constraining also functions during the cloning process, greatly simpli- fying alignment of multiple fields that are to be In a column or on the jiFTu-; same horizontal plane. Let's do some more cloning to demonstrate: ' ' , 1 . In the background editing mode and with the Field tool selected on the Tools palette, click on field number 3. Its border wUl turn into a marquee (or marching ants, If you prefer). 2. Now, simultaneously hold down the Option key (for cloning) and " ' the Shift key (for constraining) simultaneously. , ; 3, Click and drag on field number 3 hi a downward motion. A copy of fleld number 3 (this one wUl be field number 4). will follow the cursor on the screen. AR About Fields 155 4. Place the new field directly beneath field number 3 (Figure 9- 22), Release the mouse button, but keep holding down the Option and Shift keys, 5. Now click and drag from field number 4 to the right. Yet another clone (field number 5) peels off, following the cursor (Figure 9-23). 6. Position this last field directly next to field number 4 and release the mouse button and all keyboard keys, - Cloning text fields, particularly with constraining, is a fast way of setting up columns consisting of many fields. While you clone the fields, too, you can dictate the order of tabbing that the browser will encoun- ter— without you having to go back into the background layers later and adjust the layers closer and farther. Therefore, before you start cloning fields on a raany-flelded card , plan out the order In which you wish your browsers to tab through fields. In a two-column arrangement, for example, you may want the tab progression to be down the left-hand column, then down the right-hand column. To keep the fields in this order from the very beginning of your ■ I j Field 2 ] Field 3 ' 1 11. I Field 4 Figure 9-22. Option-Shift-dragging a cloned Jieid constrains the movement to either the vertical (above) or horizontal axis. Field 2 Field 3 Field 4 Field 5 Figure 9-23. Use constrained cloning to alignjields informs. 1 56 HyperCani's Authoring Environment design process, you would create the first field at the top of the left column and begin cloning verticEilly, using the vertical constrain to keep the fields in columnar alignment. Then clone the top left-hand field again, but constrain for horizontal motion only. Drag it into position at the top of the right-hand column. Continue cloning vertl- j'.i cally down the right-hand column with the constrain key in force. Remember: Each time you clone a field, that new field is added as the . , topmost layer of the domain in which the original lives (that is, background or card). . . . . ■ I ,y.:- >.s^-, : ,<,,i • fl) ' ■. . r, '>, ,■ ■ :•• Changing a Field's Domain - . ] \ ] . The greatest hazard in creating a new text field Is making sure you are 'i]'" in the correct domain: background or card. If you discover that you've placed a field in the wrong domain- especially after carefully sizing It, positioning it, and perfecting its attributes— all your work will not be in vain. Fortunately, you can cut the entire field from one layer and paste it into the other in precisely the same location. ' We'U use our new stack, Clone Home, as a scratchpad to work with. 1 . In the Clone Home stack, pull down the Edit menu and choose New Card, • L If you were in background editing mode, this action will return you to the card level, looking at a second card in the stack. For this first part of the exercise, we want to be in the card level, not the background. 2. Choose New Field in the Objects menu. 3. Position and size the field near the bottom right of the screen, as shown m Figure 9-24. .1 if, ^ Double-click on the new field to bring up the Field Info dialog box. 5. Click the Shadow style button and OK. , . 6. Choose the Browse tool from the Tools palette. Your new shadow field should be visible on the card. 7. Pull down the Go menu and choose Previous. You will see the first card of the stack, but no shadow field. What happened is that the field you created was a card field, specific t' i to the second card in the stack. It will not appear on any other card in the stack. If you want that field to be on all cards, then you must cut Aii About Fields 157 ifc Fife Edit Go Tools Objects Figure 9-24. Adding a shadowed card-domain Jieid. This Jield will not appear on any other cord in the stack. it from the card it's on and paste it into the background. Here's how you do it: 1 . Pull down the Go menu and choose Next. • You should be looking at the card with the shadow field you created. .. ,, 2. Choose the Field tool from the Tools palette. 3. Click once on the field. The outline will turn into the marquee. 4. Pull down the Edit menu and choose Cut Field. The field will disappear from view, but it is safely in the Clipboard in memory. • - - > •■' 5. Pull down the Edit menu and choose Background. The menubar wUl show its diagonals to confirm that you are in background editing mode. 6. Pull down the Edit menu and choose Paste Field. The field you Just cut now appears in exactly the same spot on the screen from which you cut it. 1 58 HyperCard's Authoring Environment 7. Choose the Browse tool from the Tools palette. This brings you out of background editing mode. 8. Now Pull down the Go menu and choose Previous. ^[ ^ The new field Is now common to all cards in the stack because .s it Is In the background. Cutting (or copying) and pasting fields works In both directions, that is, from card to background and vice versa. So don't be discouraged If you discover that a carefully defined field is accidentally In the wrong domain. A cut and paste is the simple cure. Copying and Pasting Fields Between Stacks Now that you're familiar with cutting and pasting fields between layers on a card, you should be quick to learn that you can copy a field from any card in any stack and paste it into any other card or stack. You use the same commands and procedures that we've already discussed for changing layers. It's not likely that you'll be copying fields between stacks, but one case that may prove useful Is when you discover a nicely designed stack with a carefuUy measured boundary, special font attributes, and other properties that would take you sometimetoreplicateby way of the Field Info dialog box on a new field. If you encounter such a field and wish to import it Into a stack you're creating, follow these steps. n. . - (-.f ; 1 . With the Field tool (in the Tools palette) selected, click once on the field you wish to copy. You must also be in the same card or background domain as the field. 2. Choose Copy Field from the Edit menu. ' ' This puts a complete copy of the field into the Clipboard. Choose the Browse tool from the Tools palette and navigate your way to the new stack you're creating. You may issue a Go command In the Message Box, use Recent to find the miniature card of the new stack you were workhigon earlier, open the new stack via the File menu, or any other method you see fit. When you are in the appropriate domain for the new field, choose Paste Field from the Edit menu. AU About Fields 159 HyperCard automatically pastes the field into the card (or background) in exactly the same screen location as it was when you copied it. When you paste this field, it acquires the next higher field number for the new stack and is therefore added as the layer closest to your eye within the background or card domain. This wraps up our discussion about fields. It was a comparatively long one, but many of the properties of fields also apply to our next subject: buttons. CHAPTER 10 All About Buttons ! -r ; - While text fields are the information holders of HyperCard cards, buttons are the "movers and shakers" that can carry quite remarkable powers. As you have probably observed In your explorations In the stacks provided with HjrperCard, a button may be a simple navigation aid, directing your view to a neighboring card in the stack or to a specific card in another stack. A button also has the potential of finding, retrieving, posting, and manipulating information stored in text fields on any card in any stack. . , What Buttons Do Buttons perform actions. The action that a particular button carries out is determined entirely by the content of the HyperTalk script assigned to that button. That a button "runs" on HyperTalk may cause alarm at this stage, since we're still a bit away from beginning our discussion of the language. Fortunately, a HyperCard author does not need to know a syllable of HyperTalk to give liie most common power assigned to a button: linking one card to another. This action can be assigned to buttons byway of dialog box selections and a special card- linking device we'll describe in this section. 161 1 62 HyperCard's Authoring Environment Accessing the Button Tool ' " To work with buttons, you must select the Button tool from the Tools palette. Here's how: 1. Make sure you are In the Authoring or Scripting user level. 2. Pull down the Tools menu. This action reveals the Tools palette (Figure 10-1). 3. For convenience, tear off the Tools palette from the menubar, and place it anjrwhere on the screen. 4. Click on the Button tool, which is the middle icon in the palette's top row (Figure 10-2). 1 B 33 1 1 1 1 1 1 "a 1 1 o ' ' .-•'■:■■•■:»:.■' , • o ; - .-I , ?^ ■ i^ ■ ■ ■■ A O F^ure 10-1. The Tools menu - ■■ ; : :>;5!r.w .■ ... P 1 ■ y-. . ..■ ■ ■ ...?3>-:- r — T ■ - ! ■ " .-K Pi i ( ,' " -.if'i' n.\ A'. i . .iX- i, : i- ;r'>- . ' ; .v;;, "a 1 1 o --ii . . ■^.■<>. '-. . o A O Ftgure 1 0-2. Selecting the Button tool Ail About Buttons 163 Depending on the construction of the card you are viewing when selecting the Button tool, the card's appearance may change slightly, as borders of buttons become highlighted. 5. When you are finished with the Button tool, return to the Browse tool by clicking on Its Icon in the upper left comer of the palette or typing Command-Tab (Figure 10-3). You may dispose of the Tools palette at any time by clicking on Its close box, .,w *i V . - As a HyperCard author, you have many options regarding button properties. The properties we'll concern ourselves with in this section are the layer, visual, and HyperTalk properties of buttons. Linking choices wUl be covered in the next chapter. Button Layer Properties ' • ' ' HyperCard buttons can be assigned to either the background or card domains. Like text fields, each button Is itself a separate layer— like the acetate sheet metaphor we mentioned earlier. The browser, of course, perceives all buttons on a card to be essentially In one plane. As author, however, you are aware that what the browser sees may be made up of several background layer buttons and additional card layer buttons. Background buttons are those that you wish to be available on every card In the stack. They "show through" all the layers and can also "see" the Browse tool when you press the mouse button. That means, of course, that for a background button to respond to the click of the i 1 1 L _ Jl I 1 CD o A O Figure 1 0-3. Selecting the Browse tool 164 HyperCard's Authoring Environment mouse, the button cannot be obscured by buttons in layers closer to the viewer's eye nor by text fields or the card graphic layer. The button must be in the clear. ,f *, - : .,v : l ir '/sj CARD BUTTONS A button in the card domain will be visible and available to the browser only in the card in which it was created or into which It was pasted. An example of the need for a card button would be a name and address stack. If, on a card elsewhere in your stacks, you have a graphic image of a map to someone's house, you could create a button on that person's address stack card, linked to the card bearing the map. There would be no need for a button on any other card in the address stack if you had only the one map. Therefore, it makes good sense to create a card domain button for that card only. The instant you advance to any other card in the address stack, that button will not be there. You are much more likely to create card domain buttons than card domain text fields. As long as the buttons on a card are not obscured by other objects in their same domain (background or card), the precise order of button layers is not particularly important. With fields, you'll recall, the order of field layers affects the order in which the cursor advances from field ■ 5' • to field at the press of the Tab key. Buttons do not react to the keyboard; •^S ~' so. in nearly all cases, their exact order is inconsequential. You may have occasion, however, to design buttons in such a way ' ■ that they overlap or rest atop each other (Figure 10-4). If so. you may have to change the order of buttons to suit your scheme . For example, Click Here To Go Home Previous Figure i 0-4. Overlapping battons All About Buttons 165 in Figure 10^, the large button (which takes you Home) must be farther away from the viewer than the two arrow buttons. If you create the arrow buttons first, the large button will cover them up when you create it. To rectity such a situation, you'd change the button order to make the large button number one in the ranks. To change the layer of a button within a domain, you use the Move Closer and Move Farther commands in the Objects menu. We explained in detail how these commands work on adjusting layers of text fields. The principle Is identical for button layers. The Move Closer command brings a selected button one layer closer to the \'1 ewer's eye; the Move Farther command pushes a selected button one layer farther away from the \iewer's eye. BUTTON NUMBERS AND ORDER Each button, when It is created. Is assigned both a sequence number and a unique id number. The sequence number is its order within the domain. Therefore background button number 1 is closer to the "bedrock" background picture layer than button number 2. If you change the buttons' orders with the Move Closer or Move Farther commands, their sequence numbers may change. Consequently, it is often risky to refer to buttons (in HyperTalk scripts) by button number: The number may change as the design of the stack evolves. A button's ID number, however, stays with it, even after a button is deleted from a stack. Once an id number is handed out, it will never be given to another button in the same domain in the same stack, id numbers, therefore, are safe ways of referring to buttons. An important point to remember about button layers is that they are, indeed, there. Because their order does not affect perceived card properties, an author may forget that adjusting a text field layer means that it must also pass through button layers. For example, if you assign field A and buttons A through F, and then add field B, it will take seven Move Farther commands to push held B below the field A layer (Figure 10-5). The Move Closer and Move Farther commands work only within one domain; that is, you do not use these commands to shift a background to the card domain or \'ice versa. To do that, you cut and paste between layers, as we'll describe in detail later in this section. Button Visual Properties . Buttons are rectangular areas on the screen. Beyond that unalterable feature of buttons, a wide choice in the visual presentation of a button awaits the HyperCard author. All visual properties of a button are 166 HyperCard's Authoring Envtronment Field fl [ (§) Button R O Button D O Button B O Button E O Button C O Button F ■ ; (a) •• v-v - n • i •: ■ ;i * -rMf ;. ' (b) .Q..,B.ut.ton..E O Bu t ton F • ; ■ Figure J 0-5. Starting with onejleld and six buttons (a), you can add a newJkU, which automatically goes to the topmost layer of the selected domain (b). After . ■ ■ two Move Farther commands, the new Jleld moves back 2 layers (c). After a total ' of seven commands, the^field is number 1 (d). ■ .f.-'rv: ' ^ defined In the Button Info box (Figure 10-6). There are seven button styles (transparent, opaque, rectangle, shadow, round rectangle, check ' box, and radio button), plus the choices of attaching icon art to a button, showing the button name on the screen, or having the button ' highlight when you click It. OVER TWO DOZEN BUTTON STYLES By the time you apply the icon and name combinations to the seven ■ ' ' ' button styles, you end up with twenty-eight ways to show a button on the screen. These variations are displayed In Figure 10-7. Since the icon and name options affect the way each of the four button styles shows up on the screen, we'U discuss these options first. ICON BUTTONS Anyone who has used the Macintosh for some time Is well acquainted with icons. Even casual users can't miss them: Turning on the computer without any disk drive attached or diskette inserted brings Field R I ® Bullon B O Buf f oii D ..Qj.u.t.tonJ...,.Q...Butto,n..E O But t on G O But ton F * Fite Edit Go Tools Objects All About Buttons 167 1 Button n Button Name: Card tiutton number: I Cord button ID: 1 Sbouj name ^fluto blllte [ Icon... [ LlnfcTo...^ ( Scrlpt..7~] Style: O transparent O opaque O rectangle O shadoui □ V □ Name OName □ N«me ONitme Figure 10-7. Samples of possible button style and property combinations available to HyperCard authors 168 HyperCard's Authoring Environment up a Macintosh Icon with a flashing question mark. Everyone is familiar with chcking and dragging icons in the Macintosh Finder. The browser of your stacks, then, will feel right at home with the idea of an Icon button. For the HyperCard author, the primary benefit of an Icon button Is that this Is the only kind of button that has any graphics attached to it. In other words, you cannot simply draw a graphic on the screen with the HyperCard painting tools and turn It into a button that you copy, paste, or drag around the screen along with the action attributed to the button. Art for an icon Is stored in a part of the stack file , the Home stack file, or in the HyperCard application file Itself, This special part of the file Is called the Resource Fork. Not particularly a place for beginners, the Resource Fork also contains Information any program needs for such things as dialog boxes and their contents, fonts, and the application's icons. HyperCard makes it rather simple to assign icon art to a button. From the Button Info dialog box, click the Icon... button. You then see another dialog box that presents a visual catalog (Figure 10-8) of all the icons the current stack could find (In the resource forks of the stack itself, the Home Stack, and the HyperCard program file). Icons have both an id number and optional name. When you click an Icon In the Icon ID: 1012 "Return Rrroui " [ None ] ( OK I Cancel Figure 1 0-8. The Icon dialog box presents a visual catalog of icons availabkjor use in buttons. AU About Buttons 169 dialog box, its id and name are assigned to that button. You may change the icon by clicking on another icon picture. If you change your mind and don't want an icon button, click None in the Icon dialog box. You have probably noticed that very few icons are perfect rectangles, which may seem on the surface to violate the rule stated earlier that all buttons are rectangular. The rule holds, even for icon buttons, no matter how irregularly shaped they are. That's because the button area that contains the icon art is stUI a rectangle. Therefore, the active area of a button is not Just atop the individual picture elements of the icon, but every spot within tlie rectangle around the icon. That rectangle. Incidentally, can be literally as large as the HyperCard screen, but the icon vrfll remain only one size. . , ICON ART AND MACINTOSH RESOURCES HyperCard comes with a number of icons already installed into the H)T)erCard application file's Resource Fork. The full set of icons and ids is shown in Figure 10-9. If you design icon art for an application to be distributed to other HyperCard users, you will have to follow several steps to convert the art into an icon resource and install that resource in your HyperCard 1000 LI 1002 1003 1004 Iii: - 1 1006 1007 1008 1019 26834 Mm #^ 18814 27056 <> 15420 16560 6720 16692 10 and 10-1 1 show what the browser and author see In a card from Actlvision's Business Class stack. Another example would be in a predominantly textual card. If you ; ' \ have further explanations about key words on the card, you may mark them with an asterisk or other character in the text field. Then overiay 's A transparent buttons atop the asterisks or atop the word and asterisk. Clicking on these buttons brings the user to a different card with the : ; detail text. This kind of instant expansion and linking of text is in the J . tradition of the concept hypertext, pioneered by Ted Nelson. So, you see, transparent buttons can be quite useful , even though the i ' browser doesn't "see" the button per se. It's up to the stack author to . : make the browser perceive a button when there is none to see. Figure 10-10. This map has many transparent buttons atop tt, each leading you to an adjacent country's map. All About Buttons 173 figure 10-11. Holding down the Option and Conmumd keys reveals the locations of all the transparent buttons on the map. , ; .■ . , : •TV'*. OPAQUE BUTTONS An opaque button appears to the browser as a rectangle that doesn't let any objects behind It show through. Without any background graphic to invite the browser to "click me," this button style begs for the Show Name attribute to be checked, an icon, both the name and the icon, or, surprisingly, a graphic In a layer between the button and the viewer's eye. Let's explain this last idea. In all our discussions about the interaction between background and card domains, we've made it sound like anything in the card domain graphic layer obscures objects beneath it, that is, in the background domain. Visually, that's correct. But buttons have a kind of X-ray vision that lets them look at the surface level cursor through the card picture layer. Therefore, if you have an opaque button in a background layer, you can put a card level graphics image directly between the button and the viewer's eye. To the browser, the graphic may appear to be a background graphic under a transparent button or like an icon button altogether. But what the arrangement of background opaque button and card layer graphic gives you Is a consistent button action from card to card, whUe the graphic associated with the button changes from card to card. If that is a desfred effect, then the opaque button is the right choice. 174 HyperCard 's Authoring En vironmen t RECTANGLE AND SHADOW BUTTONS By selecting the rectangle button type, you instruct the button to show Itself clearly to the browser with a single line border around the rectangle defining the area of the button. Because the area Inside the border is opaque, no graphics or text fields beneath the layer of that button will show through. Therefore, this button style is usually best suited for those that show the button name. Icon and combination Icon and name buttons are also not unusual with a rectangle style button. What we said above about a card layei graphic and a background button also holds true for a rectangle button. The button will "see" the cursor through a card domain graphic if you wish to change button graphics on each card. A shadow button is just like a rectangle button, but HyperCard draws a drop shadow to the right and below the rectangle, ROUNDED RECTANGLE BUTTONS The round rectcmgle style draws a shadowed round rectangle inside the rectangular area of the button. This button style will look familiar to most Macintosh users, since it and versions closely related to it are used commonly in dialog boxes. Buttons that show the button name look particularly appealing in this button style. Round rectangle buttons are also opaque, and observe the same layering properties as opaque, rectangle, and shadow buttons, detailed above, CHECK BOX BUTTONS ■ " A favorite button style from Macintosh dialog boxes is the check box. Use this button when you wish the user to turn features on and off. According to published Macintosh user interface guidelines, check-box buttons do not interact with other buttons {as radio buttons do), so each one should control a toggled selection of some kind, WhUe a cHck of an unchecked check- box button should place an X in the box, this action must be carried out by the button's script. Therefore, until you learn about HyperTalk, you'll have to limit your check-box ventures to copied and pasted varieties from other stacks. In almost every case, you'll want to show the name of the button to tell the user its purpose on the card. RADIO BUTTONS -^i- - ' ' ' • ' ' ^ According to the Macintosh interface guidelines, radio buttons are usually grouped together in sets of two or more. They should behave in a way that lets only one button In the group be engaged— set with a All About Buttons 175 black center dot- at a time. Hence Its derivation from the old car radio pushbutton model. The actions that highlight and unhlghlight buttons in a group are controlled strictly by scripts- and carefully conceived scripts at that. As one button Is clicked, Its script must unhlghlight the others and highlight itself. It's not as difficult as it sounds, but it's also not something you're likely to do before diving into HjrperTalk. A radio button, like a check box button, should show the button name to help identify its meaning. Always check the Show Name property in this style of button's Button Info dialog box. HypefTalk Button Properties . . ; . Without getting into specifics about HyperTalk at this stage, we can say that HyperTalk scripts may frequently refer to specific buttons in a HyperCard stack. For example, you may find yourself writing a script that includes a statement to essentially click on a card's button. That is, the script will perform several operations on your behalf, one of which is cHcking on a particular button to effect that button's action. For this to happen, the button needs a name, whether you show it with the button or not. You may not start writing these kinds of scripts right away, but it would be a good idea to get in the habit of assigning names to buttons. Chances are that the exercise wUI actually help you in your card design by forcing you to think through exactly what purpose each button has on the card. To the best of your ability, assign a one- or two-word name to the button that closely describes the action that the button performs. ■j^V • ■ji'/.jw ■ ,;; ;-.r? ' ' Creating New Buttons If you were with us when we created new text fields, creating new buttons from scratch will be a breeze. The techniques are identical. As with fields, the biggest trap to watch for is being in the desired domain (background or card) before creating a button. In the haste to make buttons, it's easy to forget to choose Background from the Edit menu when you desire background buttons. Here, then, is one of the two ways to create a button: 1 . Creating a button is an authoring task, so be sure you are at the Authoring or Scripting user level. 2. If you wish to make a background button, choose Background iirom the Edit menu, or type Command-B. 1 76 HyperCard 's Authoring Ern}ironTnent 3. Choose New Button from the Objects menu. A default rounded rectangle- style button appears In the center of the screen. The marquee is already swirling around It, indicating that the button is selected and the Button tool is in force. The other button creation method takes these steps: 1. Pull down the Tools menu and select the Button tool. 2. Hold down the Command key. When you do, the cursor changes to a "plus" sign. This is bke a drawing cursor. 3. Position the cursor at the upper left comer of the location on the screen where the button is to appear. 4. Click and slowly drag the pointer to the right and down (Figure 10-12). u-' ■ ?" As you do, the outline of the button's rectangular area shows n- • u you the extent of the button you are dragging. 5. When the button is the desired size, release both the mouse button and the Command key. ,1 The default button style for the New Button method is a rounded rectangle . with no icon, but showing the New Button name . If that's the kind of button you want, simply select the Browse tool in the Tools palette to return you to the card layer (if you were in the background). For the Command-drag method, HjrperCard dishes out a transparent style button with neither name nor icon properties set. Of course, no matter which method you follow, you haven't instructed the button to do anything, so clicking it with the Browse tool results in no action. We'll show you how to give the button life in the next chapter, on linking. Rarely will the default button style be the one you want, nor will your first attempt at dragging the button always be successful at placing and sizing the button as you had plarmed. It's then time to edit the button. MOVING AND RESIZING BUTTONS - ' v ; . As far as the button's size and location goes, you can adjust them most simply right after you create it, before selecting the Browse tool. When ! / you create a button, the new button is selected, as noted by the marquee (or marching ants) around the button's rectangle. When a button is selected, you can drag it around the screen and resize it. AH About Buttons 177 Figure 10-12. To create a new buttonfrom scratch, select the Button tool hold down the Command key, and drag the button to the desired size. To drag the button while it's selected, place the screen cursor in the center of the button's rectangle, click, and drag the button. As with text fields, you have the ability to constrain movement along one axis. Before clicking and dragging the button, hold down the Shift key. If you start dragging the button up or dovm, you will be restricted to movement In the vertical direction only, no matter how you move the mouse cursor; similarly If you drag the button first to the left or right when the Shift key is pressed, your drag motion will be constrained to the horizontal axis. Resizing the button is a similar process, except that you click the cursor on one of the comers of the button's rectangle and drag that comer like a rubberband. Release the mouse button when the button is the desired size. Constrained movement with the Shift key is adso available when resizing buttons, in case you have carefully adjusted one dimension and need to adjust the other without disturbing the first. Hold the Shift key down before clicking and dragging the button's comer. When the button style is checked as Round Rectangle, the Shift constrain on resizing performs one special feature that aids in uniform- ity of button size on a card. By holding down the Shift key and grabbing a comer of the button's rectangle, HyperCard automatically sizes the vertical dimension of the button to one size for all round rectangle buttons. That should ease the design burden for those not steady with the mouse. If you change your mind, and don't want that button there at all, you can delete the button two ways. First, select the button and choose Cut Button from the Edit menu (or type Command-^. Second, select the button and press the Backspace key. You may move, resize, and remove buttons at any time, even after you've used the stack for some time. Cloning Buttons on the Same Card > ■ If you've sized a button and assigned visual properties to it. you may wish to duplicate it one or more times on the same card. As with text iields, you may clone, or "peel off," copies of a button with the aid of the 178 HyperCard's Authoring Environment Option key. To demonstrate how this works, use the Clone Home stack you made In our discussion about text fields. 1. PuU down the File menu and choose Open Stack... 2. In the resulting standard file dialog box, select the file Clone Home and click Open (or double-click on the Clone Home file name as a shortcut), 3. When the stack appears on the screen, choose Background from the Edit menu or type Command-B. <, The menubar will display its identifying background hash marks. You should see outlines for the fields originally in the stack and those we made in the last section. At the bottom of the , card are two buttons, whose actions point to the previous and next cards in the stack, 4. Tear off the Tools palette and place it hi a lower comer, 5. Choose the Button tool from the palette. . r." , 6. Hold down the Command key and drag the outline for a new i . r button in an open area on the screen (Figure 10-13). | 7t'-^' Double-click on the newbutton's outline to bring up the Button j Info dialog box. i 8. Select the Round Rectangle button style, and click on the Show ; Name checkbox, 9. Type the name "Button 1" into the name blank (Figure 10-14}, and press the Return key to close the Button Info dialog box. ; When you return to view the card, you'll see the round rectangle | button with its name in the center, and the marquee around the | button's rectangle. If you wish to see what the button looks like to the I browser, select the Browse tool in the Tools palette. Then reselect the Button tool, because we are about to edit the new button we just created. > 10. If the new button's outline is not a marquee, click once on the \ ■ - I S ^ button to select it. j 1 1 . Hold down the Option key, and click and drag on the new button | to the right of the first button (Figure 10-15), [ An exact copy of the first button peels off the first, ready for you 1 to place anjrwhere you wish. This second button is in a separate [ layer, actually the topmost layer in the background domain, j ' since it is the most recent object added to that dornain. i Notice something quite important: The exact copy of the button j includes an exact copy of the button's name . If you double-click on the j AU About Buttons 179 4 File Edit 60 Tools OtpjectV □ a 0 A 0' „l> if:.!; J^ure I0-J3. Com/Tiond -dragging a new button Button 1 Button Name: Card button number: 1 Card button ID: 1 . . ; S Shouj name □ fluto hilite Icon... LinkTo.iT^ Script... Style: O transparent O opaque O rectangle O shadoui (S) round rect O check boH O radio button Cancel Figure 1 0-14. Assigning the name Button 1 in the Button Info dialog box. Note that the Round Rect style and Show Name property are selected. 180 HyperCard's Authoring Environment Button 1 Figure 10-15. Holding down the Option key and dragging from the Jirst button 'peer off a clone button. The clone has exactly the same settings as the orlgtnal. new button while it's selected and inspect the Button Info dialog box, you'll see that the only information about the new button that differs from tlie first is its number (it is now in a different layer) and Its id number. When a button displays its name and you clone buttons from It, you will have to double-click on each new button and change Its name. That turns out to be much easier than creating a series of new buttons from scratch and aHgrdng their sizes precisely so that all buttons match. Bear in mind, too, that you c£in constrain the movement of a clone when you are peeling it from its parent. Therefore, if you wish to place a pair of buttons In precisely the same horizontal or vertical axis with each other, you can hold down the Shift and Option keys before dragging the clone away from Its parent button. Changing a Button's Domain Although you cannot use the Move Closer and Move Farther commands ■ to shift a button between backgrotmd and card domains, the procedure t to shift domains requires only a few simple steps. You'll probably need to do this most often to transfer a background button mistakenly created In the card domain. To demonstrate how this procedure works, you'll perform one last experiment In your Clone Home stack. 1. While looking at the Clone Home stack, pull down the Edit menu and choose New Card. I ? ■ • If you had been In the background editing mode, this action will ■ return you to the card domain, looking at a new, blank card in the stack. For the first part of this exercise, you want to be In the card domain, not the background. 2. Choose the New Button hi the Objects menu. 3. Double-click on the new button to bring up the Button Info ; ' ' dialog box. All About Buttons 181 4. Click the Icon.. . button and choose the HyperCard stack icon from the icon dialog box. 5. Now select the Browse button on the Tools palette. , You see the Icon button you Just created. 6. Click on the left-facing arrow button at the bottom of the card. Tills action takes you to the previous card in the stack. Notice that your new card level button Is no longer visible. As a card button, it exists only on the card in which it was created. If you want that button to appccir in every card, then you must transfer it to the background. Here's how: ; ' 1. Click on the right-facing arrow button to bring the card with your new button into view. 2. Choose the Button tool from the Tools palette. 3. Click once on the button. The button will display a marquee outline. 4. Choose Cut Button from the Edit menu (or lype Command-X). The button disappears from view, but it is safely in the Clip- board in memory. . > v , ,v numbers in the monthly calendar could be either in card domain text , ,^ . . , - fields or in the card graphics layer. Each button would contain a hard .. . link to the corresponding day's card in the appointment book stack. That means, however, that we would have to create twenty-eight to thirty-one card domain buttons per monthly calendar card and estab- lish the Unks one by one— 365 of them for a year. SOFT UNKS There Is an easier way. although It means establishing a "soft" link. For this setup, you would create the monthly calendar stack with a small background text field in each daily square of a blank calendar form. Now, you can fill in the numbers for each day in the small fields of your calendar stack— one card for each month. After that, change the properties of the background fields in such a way that they are Locked Fields. This turns a field into an ad hoc button. Instead of the hard link between monthly calendar day and the appointment book, you would then write a short HyperTalk script that performs a soft link. The script would combine the date number inside the field you click with the name of the month and year for that card into a full date, such as September 1 1 , 1990. Next, the script would perform , . the hard link part of the operation, going to the first card of the , appointment stack. Finally, the soft link part plays its hand, as the script orders HyperCard to fmd the fuU date among the cards in the appointment book stack. The convenience of this kind of soft link to an author should be ,^ ,- , .. obvious. You need vinite only as many links as there are squares In the monthly calendar form, not one for every day of the year. Moreover, as " , .' time marches on, you can add months to the calendar without adding one letter of HyperTalk script to accommodate links to the new dates. Admittedly, soft links require knowledge of HyperTalk. We unasham- edly present this example at this relatively early stage in your Hyper- ... Card learning as enticement. We hope you don't stop short of getting . into HyperTalk. Instant Link Scripts ' ^ /. We've come to the part that shows you how to have HyperCard make • • button scripts that link one card to another— automatic hard links, if i : J you will. The procedure revolves around the one button in the Button Info dialog box we haven't yet covered: the Link To,., button. ' When you create a new button and double-click on its outline, you get c V. that button's Button Info dialog box, in which you set its visual Basic Linking 189 Go to destination, tiien aim link at: This Card [ This Stack 1^ 1 Cancel Figure 11-1. The Link To button produces a small window to help yoti establish the link. properties. At that point you can also establish a hard link action for the button. The outline of the process is covered in three simple steps: 1. Click on the Link To... button, which displays a small window with instructions (Figure 11-1}. 2. Navigate your way to the card to which you wish to link. 3. Click the This Card button on the overlajdng window. With the click of that This Card button, HyperCard generates a "Go to" entry in the button's script, complete with the exact designation of the destination card. If the destination is in the same stack, it signifies the card by its id number. No stack name Is entered, because the current stack is implied in the script when no stack name is provided. If the destination card is in a diflFerent stack, the line of the script identifies the card's id number and the stack's name. Let's experiment with this power, 1 . Go to the Home card. - 2. Choose New Button from the Objects menu. ■ 3. Double-click on the new button, which should still have the marquee around it, 4. Type the name Test Button into the Name box. 5. Click the Round Rectangle radio button in the list of styles (Figure 11-2). 6. Now click the Link To... button. A mini window appears on the screen, advising you to go to the card to which the current button should be linked. 7. Click on the Weekly icon in the Home card (Figure 11-3). HyperCard will bring the Datebook stack into view and advance to the current week, 8. Click twice on the right facing arrow, bringing into view the card of two weeks ahead of the current week. 190 HyperCard's Authoring Environment Test Button Button Name: Card button number: 23 Card button ID: 72 ^ Shoui name M Ruto hilite Icon... LinkTo... Style: O transparent O opaque O rectangle O shadow lund rect leck bOK O radio button ® roi Qchi [ Script... ] ( OK I Cancel Figure 1 1 -2. Clicking the round red button style for Test Button Go to destination, then aim link at: This Card^ [ This StacIT) [ Cancel [ To Do gf Test Button ]) fiSl EH Calendar Figure 1 1 -3. Clicking on the weekly appointment book icon on the way to establish the link between the Test Button and a card in the Datebook stack Basic Linking 191 9. Click the This Card button in the mini window. This tells the button named Test Button where it should "go to" when you click on It in the Home card. After speciljdng the link, HyperCard brings you Immediately back to the card with the new button on it for further editing or additions. Before we try the button, let's see what HyperCard did for us in this button's script. 1. Choose the Button tool from the Tools palette. 2. Double click on the new button. 3. Click on the Script button In the Button Info dialog box. Notice that the script now contains a line that says "Go To card ID 4012 in stack 'Datebook'" (the id number in your script may be diiferent). H3rperCard wiU perform this action whenever the cursor is atop this button when you release the mouse button. Now, click Cancel In the Script dialog box, and choose the Browse tool in the Tools palette. Click once on Test Button, In a flash, you are looking at the card in the Datebook stack to which you linked. As we mentioned, there is no link created for you in the other direction. You can, of course, go Back (in the Go menu) step by step. In case you want to see where you have been. If you're not happy with the link you have made, you can change It, using the same Link To... button in the Button Info dialog box and procedure we Just walked through. The new link you establish will replace the first one written into the script. In a way, then, you can edit the button script without even opening the script dialog box. New Button Strategies Now that we've seen the component parts of what goes into a button, including a hard link, we present a prescription for creating new buttons most efficiently. You don't have to follow our orders, but we've found this procedure to be the least time-consuming. If you are Command -dragging a new button, don't be too concerned about accurate placement or sizing at first. Just get any kind of button outline on the screen. With either button- creation method, double-click on the button, since It is still selected (has the marquee around it) when you release the mouse button from creating it in the first place. Go to work on items In the Button Info dialog box. 192 HyperCard's Authoring Environment Assign a name to the button (optional, but recommended). Now grab the mouse and start selecting the remaining visual attributes. First, if the button is to show its name, click the check box. Then set the button style from the list of seven on the right of the dialog box. Now we come to the automatic scripting. Click the Link To... button. Follow the directions on the mini window, as we described above. Whsn you're finished, you'll automatically come back to the card, ready to use the button. Now that the button is In its proper style and is correctly linked, you can select it and adjust its location and size to suit. Remember to use constraining for fine-tuning both location and size. Also, since so many of the button's attributes are already set, you can clone the button If needed. The only adjustments you'll need to make to the Button Info dialog box for each cloned button are the button name and in the Link To. . . button. Follow the mini window's directions for each button to make sure it links to the desired card. You're now ready to accomplish quite a lot with new buttons of your own creation. The only area we really need to cover for all HjrperCard authors (HyperTalk and non-HypeiTalk) is what all those painting tools are about. I: b. . ; ' CHAPTER 12 Introduction to HyperCard's Painting Tools With the help of the stack, card, and button ideas included on your HyperCard disks, you can go far creating your own stacks that have a great deal of visual appeal and Information storage power. But there will be times when you'll want to modify the background art on one of those stacks. After all, the purpose of the "ideas" files provided with Hyper- Ccird is not Just to give you "ccinned" stacks that you adopt blindly. They are intended as starting points to stimulate your thinking about the way you can use HyperCard to manage information. It probably won't be long before you'll want to take that grander step and design a new stack from scratch. The Role of HyperCard Art What you'll begin to appreciate with your first explorations in Hyper- Card stack desi^i is that no matter how powerful the button actions you assign to a card or how interactively cards link with each other, the overall "look" of the card will have a pervasive impact on the stack's appeal. To that end, HyperCard provides the author with a very complete set of artistic tools— the same kinds of tools that professional Macintosh artists have been using since the Macintosh became avail- able in January 1984. We would be leading you on if we said that these tools turn anyone into an accomplished artist. As with any tool, the quality of the work 193 194 HyperCard's Authoring Environment resulting from the application of that tool is directly proportional to the skill of the user. Someone using a hammer for the first time will more than likely drive a nail in askew or perhaps miss the nail's head and damage the wood surface. With practice, however, you get a feel for how a nail responds to various pressures of the hammer's head in different types of wood; you learn, for Instance, when to stop hitting a wood finishing nail before its head reaches the wood surface and then to carefully recess the nail with the aid of a tamp. What this means is that you can expect to gain a comfortable skill level by practicing with the HyperCard graphics tools. They'll give you a headstart in many graphical areas. If you can't draw a straight line on paper with a ruler and pencil, don't fear: One HyperCard tool draws straight lines, no matter how crookedly you drag the mouse pointer. Other tools help you draw perfect circles and squares. Still otiiers fill areas on the screen with Intricate patterns and shades. Practice Is the best way to gain mastery of the graphics tools. But you are also free to examine the techniques of those who have gone before you to create the screens of existing stacks. We'll show you in chapter 1 5 how to literally put a magnifying glass on their work to see how they accomplished various graphics effects. If they did it, so can you. Macintosh Painting , j : x , , ; . . The basis of the HyperCard graphics tools is known by a couple of terms .,V among Macintosh users. One term you'll see sometimes In this regard is "bit- mapped graphics." Bit- mapping Is a term borrowed from the programmer's lexicon, meaning being able to turn on or off each tiny dot on the screen. We won't be using this term much, because it tends to get confused with the Macintosh's nature as a bit -mapped graphics computer. Not all Macintosh graphics programs give you direct control over each dot on the screen, but the Macintosh nevertheless draws everything on the screen dot by dot. PAINTING VS. DRAWING . , , . . .^>.,,, u We prefer to call the HyperCard graphics tools painting tools, as distinct from drawing tools. Both terms are derived from two early graphics programs that Apple released for the Macintosh. The first was MacPaint, written by the same Bill Atkinson who designed HyperCard. The other was MacDraw, adapted by Mark Cutter from his LisaDraw, a program on Apple's earUer Lisa workstation computer. By examining the difference between these two environments, you'll understand quite a bit about HyperCard's graphics environment. • =■ - '•' "v G oial Introduction to HyperCard's Painting Tools 195 MacPaint, which is still a popular graphics program on the Macin- tosh, gives you control over each dot on the screen (a dot is better known as a picture element, or pixel). When you draw a rectangle in a "paint" environment, you are actually laying out a pattern of black pixels atop a white background. The graphics document you store on the disk doesn't recognize the pattern of pixels as being any kind of graphics object. It simply stores the locations of black pixels on the page— a map. If you will, to the on and off bits on the page. Since the rectangle Is only a set of pixels, you cannot "pick it up" to adjust Its size or line thickness. MacDraw, on the other hand, treats graphics shapes as objects Instead of a collection of dots. For Instance, when you draw a rectangle In a "draw" environment, the program stores information about the shape as an object. A rectangle has a screen coordinate for its top left and bottom right comers, a certain width of the line that makes the rectangle's four sides, and a certain pattern that may fill the rectangle. You can select and "pick up" an object at any time after you draw it on the screen and change any of its attributes: its size, location, line thickness, or pattern. Draw objects, then, have layers, just like HyperCard's text field and button objects have layers. What you can't do with a draw program, however, is adjust individual pixels on the screen for certain artistic touches, such as gradation of shading or fine- tuning complex graphics one pixel at a time. Each kind of program has had versions produced by third-party software developers. In the paint environment, FullPaint (Ann Arbor Softworks) has been popular. Cricket Draw (Cricket Software) improves on MacDraw. One program, SuperPaint (Silicon Beach Software) combines both the paint and draw environments into one, each environment getting Its own layer domain In a document. HYPERCARD PAINTING HyperCard's graphics tools are in the paint tradition. Everything you create with the graphics tools will be painting pixels on the screen. You can apply the tools equally to the background and card picture layers. The layers can even interact with each other for some special effects you can't get with regular paint programs. If you've had experience with paint programs such as MacPaint. FullPaint, or SuperPaint, HyperCard's painting tools will be familiar to you, Ttiere are a number of enhancements over MacPaint, however, so don't think you're getting old stuff in this program. If you're new to Macintosh graphics, you're In for a treat. Paint graphics are fun on the Macintosh. You'll be surprised at the results you'll be getting in a short time. The best part, though, is that there is 1 96 HyperCard 's Authoring Environment r ; no penalty for trying any kind of drawing or technique. If it doesn't work, then erase it and try again. Experiment freely. After an overview of the HyperCard painting environment, we'll p i f present each of the HyperCard paint tools, commands, and shortcuts. ■ As we discuss each one, try It out on your Macintosh. Only by practice will you become proficient with HyperCard's painting tools. Graphics Overview In all your HyperCard painting, you'll be turning pixels on and off. Since a HyperCard graphics layer can be the size of the entire HyperCard window, the maximum area is 512 pixels across and 342 pixels vertically. The exact number isn't particularly important, unless you're trying to figure out how many pixels wide to make a certain number of recurring elements so that they all fit on the screen. Macintosh screen pixels are square. This accounts for their remark- able clarity, especially on the monochrome Macintosh screens. Round pixels, as found on many other computers' screens, tend to create fuz^ edges on graphics and text characters. Most of the time, you will be working with the pixels at a density of approximately 72 pixels per inch. At this density, individual pixels are distinguishable, but quite small. Don't expect to work with individual pixels at this scale right off Your ability to work with single pixels at this level will grow with experience. For more detailed work, you'll be able to zoom into your work in a scale ' : made for single- pixel work— FatBits, It's called. Still, at the regular ■ ' scale, you'll be able to use HyperCard's painting tools to draw polygons, circles, lines, free- form shapes, and text. You'll use FatBits for any fine- tuning you deem necessary. BACKGROUND VS. CARD LAYERS WhUe it's true that you're painting with pixels on both the background and card graphics layers, the two blank layers are very different. This difference wUl affect the way you paint on each layer. The background layer, as "bedrock" for the entire card the browser ■ sees, comes up looking like a white layer. In other words, it is a blank layer of 5 1 2 by 342 white pixels. Images you paint on this layer wiU be blackening whatever pixels are necessary to convey your graphics image. " ' In the card graphics layer, however, the blank card is actually ' '' transparent— a 5 1 2 by 342 grid of clear pixels. Sitting atop an all-white background graphics layer, the card graphics layer appears white. Introduction to HyperCard's Painting Tools 197 What you're seeing, however, is the white of the background graphics layer showing through the transparent card graphics layer. This means that if you wish to have a card layer graphic contain white area when the entire background graphics layer is shaded grey, you would have to paint that white area in the card layer. We'll have more to say about this later but the concept is a fundamental one you should be aware of right now. When you get an unexpected result with a paint tool, it is usually attributable to the differences In the properties of these two graphics layers. , - , ; PAINTING MENUS HyperCard strives to keep the complexity of menus to a minimum at all times. Therefore, the menus associated with the painting tools are hidden until the instant you select one of those tools. To activate the painting menus, pull down the Tools menu and select any of the painting tools below the dividing line in the palette (Figure 12-1). The Objects menu disappears, and three new menus appear In the menubar: Paint, Options, and Patterns (Figure 12-2). The instant you select one of the three object tools at the top of the Tools palette (BrowBe, Button, or Field), the painting menus disappear, and the Objects menu reappears. You wUl find it most convenient to tear off the Tools palette when working extensively with the painting tools. Place the small palette window in a spot on the screen where it wUl be out the way of your painting. You can drag it around during any paint operation. Tools o r — T 1 1 ■- . 1 P 1 1 o o c? A o d Object Tools - Painting Tools Ftgwe 12-1. Below the object tools in the palette are fifteen painting tools. 198 HyperCard's Authoring Envirorunent Paint ^^^^^^^^H Options ^^^H Select Grid Select nil FatBits Pfiiifpr If Piic 1 U LLP CI 1^ C U 3 Fill 1 nuert ■ Pickup Brush Shape... Darken Edit Pattern... Lighten Polygon Sides... Trace Edaes Rotate Left Dram Filled Rotate Right Draw Centered Flio Uerfirfil Dram Multiple riin Hfiri7i^n'lfil Opaque Transparent Keep %K Reuert Patterns Figure 12-2. When you select a painting tool, the Objects menu disappears and three painting menus appear in the menubar. The Paint menu contains a long list of Items that enhance the painting work In which you may be involved. Most of the items are actions that affect Items or regions m your painting that you Ve selected for a specific alteration. In the Options menu are several settings that affect future actions you'll take with various tools. Many of these Items are swltchable (that is, they can be turned on or off), while the rest produce graphical dialog boxes to choose one of many possible settings. Those that produce dialog boxes are also accessed from the Tools palette by double-clicking on the affected tool (see below). Finally, the Patterns menu is a tear-off palette of all the patterns with which you may draw or fill enclosed areas. In an active graphics session, you will probably find it convenient to tear off the Patterns palette Just as you do the Tools palette, particularly if you need to experiment with various patterns to achieve a desired graphics effect. Introduction to HyperCard's Painting Tools 199 Undo — the Savior HyperCard's painting environment would be anything but inviting if you couldn't easily undo experiments with the tools. Despite HyperCard's tendency to save changes to the disk at every turn, it is far more forgiving when you are using the painting tools. You can try different effects and undo those that don't w^ork. Perhaps you want to try filling an area with different patterns to see which one looks the best; or perhaps you would like to compare the effect of difi'erent paintbrush styles when embelhshing a graphic. HyperCard's painting Undo com- mand gives you that freedom. Whenever you are in the painting tools. HjrperCard remembers the last action you took- cutting, rotating, filling, anything. If you see that an action brought you unexpected results, or at least results you don't want to live with, you can immediately undo the action three dlff^erent ways. One way to undo is to choose Undo from the Edit menu. A slightly more convenient way for the more experienced Macintosh user would be to type Command-Z, which Is the keyboard equivalent of the Undo command. The fastest way, however, is to press a special Undo key— the tilde key. On the Macintosh 512K Enhanced and Macintosh Plus, the tilde key is located to the left of the 1 key at the upper left comer of the keyboard (Figure 1-16J. On the Apple keyboard for the Macintosh SE and Macintosh II, the tilde is located to the left of the spacebar. Pressing this key is the same as choosing Undo from the Edit menu. Pressing it again brings your erroneous action back onto the screen. You can use this toggling action to your advantage when you are trying to compare two techniques. When you decide on the choice you wish to stay with, just leave it on the screen and proceed to your next action. This particular kind of Undo— a single action— remembers only the last action. If you make a boo- boo and perform another action after it, you won't be able to undo the boo-boo. We've divided coverage of HjrperCard's painting powers into three chapters: The first deals with the choices in the Tools and Patterns palettes, the second with the actions in the Paint menu, and the third with the choices available In the Options menu. We'll then finish our tour of painting with a chapter on painting strategies within Hyper- Card. • . .. - CHAPTER 13 HyperCard Painting Palettes We'll stast our tour of all HyperCard painting tools wtth the tools in the Tools and Patterns palettes. The presentation for each tool will be as complete as possible, including all variations for using the tool with Option, Commeind, and Shift keys, where applicable, and any short- cuts that accrue to the tool. In this way, you'll end up with a reference work to which you can refer when designing your own stacks. If at all possible, work through this chapter in front of the computer, so that you can try these tools and their variations. The Selection Tool One of the early techniques you learned with your Macintosh was selecting text to do things like cutting, copying, and changing font properties. The paradigm was 1} select the material to be changed, and 2) make the change with a menu command (or keyboard equivalent) . That same paradigm also applies to HyperCard painting work. What's different, however, is the way you select the material to be altered. Instead of dragging a black area over the material, you surround it with a selection outline. This kind of outline is very noticeable on the screen because it looks like the lights flashing around a theater marquee or, as some have suggested, marching ants. Eveiything mside the selection outline is selected; the next menu command that affects a selected item wiH work on everything inside that outline. 201 202 HyperCard's Authoring Environment There are two types of selection outlines in HyperCard: the Selection tool and the Lasso. Our discussion here focuses on the Selection tool (the Lasso is covered next). With the Selection tool, you can select a rectangular area on the screen. To do so, follow these steps: 1 . Choose the Selection tool from the palette by clicking once on its icon. -s; ; ii -5 2. Place the screen cursor at the top left comer of the rectangular area you wish to select. 3. Click and drag to the right and down from that spot. The marquee will expand to follow the mouse pointer {Figure 13-1). 4. When you are at the bottom right comer of the desired rectan- gular area, release the mouse button. The marquee will still "sizzle." E>verythlng In that rectangle, including white background around the target shape, is selected. The next menu action you take— If it acts on a selection— will affect every pixel inside that . :i> rectangle. We'll see what most of those actions are in our ' , discussion of the items In the Paint menu In chapter 14. Holidays 0 n -a □ 0 0 A 0 1 , i: \' Figure 13-1. Enclose shapes and regions with the selection rectangle to nvave, copy, cut, or perform other operations. HyperCard Painting Palettes 203 The Edit menu also contains a few items that can act on a graphics selection. Cut, Copy, and Clear perform the same actions on a graphics selection as they do on a text selection. Cut and Copy, In particular, place a duplicate of the entire rectangle into the Macintosh Clipboard for pasting elsewhere. You would cut and paste, for example, if you accidentally begin creating a graphic in the card layer but wish to transfer it to the background graphics layer. First select the graphic, cut It, choose Background from the Edit menu, and paste it. After you perform an action on a graphic selection, the selection rectangle stays in force. Thus, if you need to perform multiple actions on a selection, you are assured that the exact same rectangular area is selected for each operation. COMMAND KEY ENHANCEMENT - - ■"' ' ■]--. You won't always want to select the entire rectangular area around a graphics image. If that's the case, you can force the Selection tool to "hug" the graphic image that would be inside its rectangle. To do this, hold down the Command key before and during the dragging of the Selection tool. When you release the mouse button, the selection marquee will snap to a rectangle defined by the image's outermost pixels (Figure 13-2). There are some rules you need to follow to make this feature work. First of all, it Is intended ideally for those times when an image is In a white background. If the image is in a pattern of any kind, the selection rectangle won't be able to snap to the Image because it wiU run Into black pixels of the pattern (Figure 13-3). That, therefore, is the key: The rectangle collapses around the nearest black pixels Inside the selection rectangle. Selection rectangle snaps back to the outermost rectangle of the shape. Figure J 3-2. When you hold down the Command key when dragging the selection rectangle, the marquee will snap to a rectangle defined by the outermost pixels of the enclosed shape. 204 HyperCard's Authoring Environment ■-.■■.■fiy:. :-:<-:-: :-:-[-:-: m Figure 13-3. Using the Command key enhancement with the selection rectangle on a shape in a pattern results in the rectangle snappiT\g to the pattern's pixels. SHIFT KEY ENHANCEMENT Once you've selected an area or image , you are free to move It about the " "j' screen. To move it in any direction, simply place the mouse pointer within the selected area, click, and drag. But If you wish to move the image In a strictly vertical or horizontal motion, press the Shift key before dragging to constrain motion to one axis. This constrain action '\ works identically to the way it does when moving fields and buttons around the screen. OPTION KEY ENHANCEMENT - ^ ; ; . ; You may also clone a selected image. This, too, is like cloning fields and buttons. After you've selected the Image, hold down the Option key, ' click, and drag. The original image remains in its original position, while an exact duplicate follows the cursor around the screen (Figure 13-4). A combination of the Option and Shift keys allows cloning an image while constraining the movement of its copy to the horizontal or vertical axis, depending on the Initial direction of the drag motion. Incidentally, if you hold down the Option key while you drag a selection rectangle around an Image, the tool changes to the Lasso, and the shape is selected as if with the Lasso (see below). Figure 13-4. The Option key enhancement to the selection rectangle lets you clone shapes or regions enclosed by the rectangle. HyperCard Painting Palettes 205 DOUBLE-CLICK SHOE^TCUT There will be times when you'll want to select and copy (or cut) the entire graphics layer, whether background or card, to paste in another stack or on another card. A quick way to do that is to first be sure you are in the desired domain (background or card) and double-click on the Selection tool in the palette. This selects the entire 5 12 by 342 rectangle of the graphic layer. Once the screen is selected, you may then cut or copy as you see fit. Remember, this selection and copying affects only the graphics layer, not the fields or buttons in the graphic layer's domain. TheLassoTool ■ - ■■ • . Like the Selection tool, the Lasso selects an image for further action. In fact, any action you can do following application of the Selection tool can be done with the Lasso. The only difference between these two selection tools is that the Lasso lets you select images that you can't initially surround with a selection rectangle. We said earlier that the Selection tool grabs everything inside its four comers. If you wish to select irregularly shaped Images amid other irregular images, a selection rectangle will invariably select pieces of the surrounding images and throw off your next action. With the Lasso tool selected in the Tools palette, you can use the mouse to draw an irregularly shaped selection edge (Figure 13-5). Simply hold down the n n o o \a O to Figure 13-5. Use the Lasso to select irregularly shaped objects or objects not selectable inside a selection rectangle. 206 HyperCard's Authoring Environment mouse button and begin drawing the edge around the image. When you J . . release the mouse button, the marquee automatically "hugs" the ^ Images within the lassoed area, even if there is more than one Item in " I the area. Notice that the Lasso hugs the items tightly, not within a .'. ^ " rectangle as in the Command key enhanced selection rectangle, above. ^ " One nice feature of the Lasso Is that it automatically finishes the loop ' " of the selection for you when you release the mouse button. In other words, you don't have to be precise In joining the two ends of your loop .' ^ \ together. In fact, If you are trying to drawalasso through a narrow gap and experience difficulty, you can let the tool do It for you. In Figure 13-6, we want to select the octagon, which Is so close to the diagonal line that it would require meticulous care to drag the Lasso tool through the narrow gap. If we start the lasso on the left side of the gap, drag it ciround the octagon, and release the mouse button on the ri^t side of the gap, the tool will finish the Job for us, SHIFT KEY ENHANCEMENT As with the selection rectangle, the Lasso selects images that can be * , moved around the screen. Pressing and holding the Shift key prior to , dragging a lasso-selected image constrains movement to the same axis , " ' as the first motion. Ftgure 1 3-6. The Lasso automatically closes the loop with a straight line between the starting point and the point at which you release the mouse button. This technique helps you select objects in t^ht places, like the octagon next to the line, above. HyperCard Painting Paiettes 207 COMMAND KEY ENHANCEMENT HyperCard's Lasso gives you an alternate solution to the problem shown in Figure 13-6. Instead of dragging the lasso around the octagon, you can also hold down the Command key and click the Lasso tool anywhere inside the octagon. The tool then selects the contiguous black pixels nearest the click point, plus any adjacent pixels. That means you can Command-click in a black object, and the entire object will be selected as If lassoed. , .y^ \ . n:. - OPTION KEY ENHANCEMENT When you hold down the Option key and drag the Lasso, you'll notice that the marquee appears a bit thicker. This signifies that the entire lassoed area- Including the white pixels- is selected. Once an area is lassoed (enhanced or otherwise), the Option key serves to let you clone the image. Hold down the Option key prior to dragging an image, and a duplicate will peel off. Holding both the Option and Shift keys con- strains the movement of the clone. DOUBLE-CLICK SHORTCUT ; \ ! i i : )id You may perform the equivalent of dragging the Lasso around the entire perimeter of a graphics layer by double- clicking on the Lasso tool. The result win be a selection of all items in the layer, "hugged" by the selection marquee If there is white space in the layer. If the layer is filled to the edges with a pattern (as with a grey pattern) then the entire 512 by 342 screen will be selected. The Pencil Tool • The one graphics tool you will probably use more than any other is the Pencil. When you hold down the mouse button and drag, the Pencil leaves a trace on the screen exactly one pixel in height and width. The "color" of the trace may be black or white, depending on the condition of the pixel under the Pencil when you clicked the mouse button. If the pixel was white, the Pencil will leave a black trace; if the pixel was black, the Pencil will leave a white line. In other words, the Pencil has the power to turn pixels on and off, one at a time. Notice that the Pencil stays in the same color as long as the mouse button stays down. If you start a black line in a white area and drag the Pencil through a black area, the line the Pencil draws vrfU remain black- indistinguishable from the black background (Figure 13-7). The reverse is true for a white line reaching a white background area. 208 HyperCard's Auttuiring Environment Figure 13-7. When the Pencil starts drawing in black, it stays in black, even when drawing over black pixels. Similarly, if it starts drawing in white pixels atop a black background, it continues to draw white as long as the mouse button is held down. The Pencil works differently from other painting tools In one impor- tant regcird: It transcends the usual barrier between background and card picture layers. When you click the Pencil in the card picture layer, the tool draws the opposite color of whatever appears on that pixel, no matter which layer's pixel Is showing at that spot. Thus, if the background picture shows a black pixel, the Pencil will draw a white pixel in the card picture layer. Hiat white pixel is on the card picture; the background picture layer is undisturbed. Because the other pednting tools don't have this black-to-white or whlte-to-black pixel propei-ty, those tools operate m one layer at a time, completely ' independent of what's happening in the other layer. SHIFT KEY ENHANCEMENT You can constrain the motion of the Pencil by holding down the Shift key before drawing. WhUe there are better tools for drawing straight lines, there are times when the Pencil constrained by the Shift key is a convenient way to paint a straight white vertical or horizontal line in a field of black (Figure 13-^). ,, . In practice, the Pencil is rarely used in the standard, 72-dot-per-lnch drawing environment of HyperCard, except by the very skilled- those who have one-pixel acuity at regular size. The Pencil is used predomi- nantly in a HyperCard painting mode called FatBits. We'll show you how to use FatBits in chapter 15. The reason we bring it up here is that Figure 13-8. The Shift key constraint is particularly helpjul in drawing straighi white lines in a black background. ■., ■ HyperCard Painting Palettes 209 the Pencil tool on the palette offers two shortcuts to zoom you into FatBits. DOUBLE-CUCK SHORTCUT ; ' " ' When you double- click on the Pencil tool in the palette, HyperCard immediately goes into FatBits. The close-up look of the card layer you're working in is automatically set to the center of the screen. You are able to scroll within FatBits, as detailed later. COMMAND SHORTCUT An even faster way to get into FatBits, looking directly at the part of the graphics you wish to adjust in this mode, is to hold down the Command key and click the Pencil cursor on the very spot of the normal-size graphic. We'll have more to say about this shortcut and other related ones in the section on FatBits. The Paintbrush Tool Perhaps the most versatile painting tool in the palette is the Paintbrush. Many painting novices avoid the Paintbrush, fearing it is a tool only for the experienced artist. While it is admittedly best applied as a freehand painting tool, even beginners can obtain accomplished effects. The Paintbrush merges two graphics concepts into a single tool: the pattern and the brush shape. You can think of the pattern as the "paint" that the brush applies to the graphics layer. If the pattern is a grey pattern, the "paint" that comes from the tip of the Paintbrush is that very pattern. The brush shape defines the apparent surface of the tip of the Paintbrush. A brush tip that is only a couple of pixels tall and wide will leave a thin trail of the selected paint pattern; a calligraphic brush tip shaped in a diagonal line leaves a different width trace of the paint pattern, depending on the direction of travel of the brush (Figure 13- Figure 13-9. A calligraphic brush style 210 HyperCard 's Authoring Environment : ' You draw with the Paintbrush just as you do with the Pencil. First select the Paintbrush tool in the Tools palette. The cursor becomes the shape of the brush. Place the cursor on the screen where you intend to begin painting. Then hold down the mouse button and draw with the mouse. It may be a single "dab" of paint by clicking and releasing the mouse button without moving the mouse, or it may be a more elaborate stroke . If the first attempt at a dab or stroke doesn't work, undo it, and try again. SHIFT KEY ENHANCEMENT Constrain painting motion by holding down the Shift key before clicking the mouse button at the beginning of the stroke . The first direction you ■ move locks you into either the vertical or horizontal axis. COMMAND KEY ENHANCEMENT " . " ,^ Whereas the Pencil automatically inverts the color of the pixel on which it starts drawing, the Paintbrush always paints in the pattern selected in the Pattern palette, even if it means painting over other material or patterns already on the graphics layer in which you're working. Remember that when we're talking about painting on the graphics layer, there is no layering within that layer. Thus overpainting com- pletely replaces whatever graphics layer pixels are m the way of the Paintbrush. HyperCard does, however, provide an option to use the Paintbrush to erase in the pattern you've selected. Just hold down the Command key before painting. The tool will turn all black pixels hito white (or transparent in the case of the card level graphics). Note that it does not Invert white into black: It Just erases black pixels in the same swath that its brush would normally paint in the pattern. When you start HyperCard's painting tools, the paint pattern auto- matically selected for you is all-black. Altering the paint pattern is as simple as selecting a different pattern from the Pattern palette (see below). You may also edit a pattern for a custom paint job (also see below) . The default Paintbrush shape in HyperCard's painting tools is a small round tip. It presents a Ime of uniform width, regardless of the direction you drag the brush across the screen (Figure 13-10). HyperCard comes with thirty-two different brush shapes from which to choose. While there is a menu choice that gets you to the brush shape selection box (described later), there's a faster way via one of the Paintbrush's shortcuts. HyperCard Painting Palettes 211 DOUBLE-CLICK SHORTCUT By double-clicking on the Paintbrush tool In the Tools palette, you bring up a dialog box that shows all thirty-two brush shapes (Figure 13-1 1). The shape with the small box around it is the one that is currently selected. To choose a different one, simply click on it in the dialog box. When you do, the dialog box disappears, and the new brush shape is in effect until you either change the shape or exit HyperCard's painting tools. When you return to the painting tools next time, the default round dot will be in effect. The number of combinations of Paintbrush shapes and patterns applied to those shapes is enormous: 1280, In case you really wanted to know. And then there's the opportunity to design your own patterns. * Figure 13-10. The default brush style is a small circle, : \ Figure 13-11. Double-click on the Paintbrush tool and you'll get the menu of brush styles available in HyperCard. 212 HyperCard's Authoring Environment The possibilities are staggering. We wouldn't presume to give you anything claiming to be even a representative sample of what you can do with these combinations. We've collected a few scribbles, however, In Figure 13-12. You'll have to experiment on your own to see how , , flexible the Paintbrush tool can really be. The Eraser Tool - ' With so many HyperCard painting tools putting black pixels on the screen, there must be a tool to get rid of them. That's the Eraser. When you select the Eraser tool from the Tools palette, the screen cursor turns into a white square. Wherever you touch that square and press the mouse button, the black pixels will turn white in the background picture layer {Figure 13-13) or transparent In the card picture layer. You can also drag the Eraser around the screen to erase wide swaths of black pixels or patterns. if "j III , IP 1 ij Figure 13-12. A potpourri of effects possible with various Paintbrush styles and patterns. Figure 13-13. The Eraser tool turns black background pixels into white. HyperCard Painting Pcdettes 213 i ^ 1^ Figure 13-14. Erasing in the card graphics layer also erases the layer's white pixels. If a background graphic is underneath, it will show through in the wake of the eraser. In the card picture layer, the eraser sometimes seems to take on an almost magical property. That's because the card layer sometimes has white pixels covering up a background graphics layer full of images. The effect seems like the opposite of erasing when background domain graphics and objects appear in the wake of the card layer Eraser (Figure 13-14). Be on the lookout for accidental remnants of card layer graphics that may obscure background domain objects. Sometimes you'll be flipping through a stack and see the text in a background field mysteriously covered with lines or white blotches. Chances are, there is a card domain white remnant overlapping the background information. To get rid of the errant white material, select the Eraser in the card graphics domain, and wipe over the affected area. The white will disappear to let the background show through without any interference. SHIFT KEY ENHANCEMENT - - - -^i'^i - '^^s As with most tools, the Shift key constrains motion of the Eraser to either the vertical or horizontal axis. This can be most useful when you need to erase graphics in a straight line. Simply hold down the Shift key. click, and drag. No matter how askew the pointer moves on the screen, the eraser action stays on the straight edge, n-^ -v/ - COMMAND KEY ENHANCEMENT We've been saying that the Eraser turns black pixels into transparent ones on the card layer. If you want to erase black pixels and leave white pixels in their place, you can hold down the Command key prior to erasing. The eraser will turn card layer graphics pixels (even those that started out transparent) into opaque white pixels. This is one way to 214 HyperCard's Authoring Elnvironment Figure 13-15. With the Command key pressed, the Eraser turns card layer pixels to white. Use this e_ffect to cover unwanted background graphics. effectively cover up a background graphic on selected cards (Figure IS- IS). DOUBLE-CLICK SHORTCUT • ^ . . , The expression "back to the drawing board" sometimes applies to a i. graphics layer you're trying to create. It isn't uncommon to try one ' ■ approach and discover that it just won't work out the way you v! , anticipated. When It's time to start over, you may as well use the stack 1 ;i file you've already created and just erase the entire graphics layer, 3 :> That's what double-clicking on the Eraser tool in the Tools palette does H i for you. It affects only the graphics layer currently in force (background 1-J or card), and not the fields or buttons In that domain. Erasing the entire graphics layer is a last resort. There Is usually something worth salvaging from an attempt at design. If so, select that part of the graphics layer with the Selection tool or Lasso and copy it. Then double-click on the Eraser to wipe the layer clean. Finally, paste • i the contents of the Clipboard onto the clean slate. You'll have a foundation on which to build, clear of the clutter you didn't like from .v; >. the previous attempt. , i I- And don't forget Undo. If you accidentally double-click on the eraser or do so when the wrong graphics layer is up, undo the damage Immediately. The Straight Line Tool > . You don't need a straight edge to draw a straight line with HyperCard's ^ ■ painting tools. When you select the Straight Line tool from the Tools ' ' palette, the cursor turns into a cross marker (Figure 13-16). The center HyperCard Painting Palettes 215 o I::::::: t 1 1 1 L 1 P 1 1 1 o A O Figure 1 3- J 6. The crms cursor of the Line tooi ■ ./ of that cross is where the "ink" comes from when you click and drag the cursor across the screen. End points of the straight line you draw are defined by the pixel on the screen where you first click the mouse button and the pixel on the screen where you release the mouse button. The straightness of the line depends on the angle you choose for the line, which is at the mercy of the 72-dot-per-inch resolution of pixels on the screen. While for many tasks, this resolution is quite good, it results in a ragged line when the angle of a line requires a stair-step effect to best fit the true geometric line between the line's two end points (Figure 13-17), Because of the nature of the screen, you will have the appearance of a true straight line only at angles in multiples of 45 degrees. Therefore, strictly horizontal and vertical lines will look smooth, as will 45 degree diagonal lines. All others may have what appear as breaks in their straightness. Still, in a full-screen painting, the overall effect of the straight line will more than likely come across to the viewer. Figure 13-17. At many angles, the Line tool produces ragged, 'stair-stepped'' lines on the screen and on printouts. The LaserWriter smooths the rough edges somewhat Forty-jive-degree lines are smooth on the screen. 216 HyperCard 's Authoring Environment If the viewer prints out the card, the stralghtness of the line in the printout will depend on the printer's resolution. An ImageWriter will imitate the same 72 -dot- per- inch resolution as the Macintosh screen. A IjaserWriter, however, has the potential of printing In 300-dot-per- tnch resolution. If you have selected Smoothing in the Page Setup dialog box, the printer will do its best to convert the 72-dpi stair-stepped line into a smooth, straight line. It still wUl not be as smooth as you would get from a draw- type program, which Instnicts the printer to generate lines in a much more geometric method: a line being a series of points between two end points. Lines may be drawn In thicknesses of 1, 2, 3, 4, 6, and 8 pixels. As you select larger line thicknesses (described below), the thickness of the cross cursor Increases to match that size. The cursor helps you place the start and end points of the line as accurately as possible. DOUBLE-CUCK SHORTCUT , ''2 ? , : V There is a menu option that lets you change the line thickness for several tools that generate lines on the screen, including the Straight i Line tool. You can bypass the menu by double clicking on the straight - - ^ K line tool's icon in the Tools palette. You go immediately to the dialog box . that presents the possible choices for line size (Figure 13-18). A small box surrounds the size currently in effect. To select a diiferent size, , j( ,i simply click on its representation in the dialog box. The new thickness ' ; remains in effect for all line-generating tools (like the rectangle and oval, discussed below) until you change it again or exit the painting tools. :.i Whenever you start the painting tools, the one-pixel -wide line thlck- i ness is In effect. SHIFT KEY ENHANCEMENT " ' ' " ' - »■ ■ ^ • Shift key constraining offers a bit more flexibility with the Straight Line tool than with others. Instead of simply constraining the Une in the horizontal and vertical axes, it allows for accurate angling of lines In I I I I I ' Figure 13-18. Double-click on the Line tool to get the line size dialog box. Ym have six line thicknesses to choose from- HypeTCard Painting Palettes 217 multiples of 15 degrees— a total of 24 fixed angles around a circle. Let's see how this works. In either the background or card domain, select the Straight Line tool from the Tools palette. In a clear area on the screen, drag a short line from a starting point and keep the mouse button down. Drag the line around the starting point in a roughly circular motion {Figure 13-19) to see how you normally draw a line to any angle. Before releasing the mouse button, press the Shift key. This turns on constraining. Now twirl the line around its starting point. You'll see that the line snaps into place every 15 degrees around the circle (Figure 13-20). Watch closely how straight the line is on the screen at each of the 15 degree mcrements. Only the lines at degrees 45, 90, 135, 180, and so on appear perfectly straight on the screen. Figure 1 3-19. FreehaiKi drawing with the LAne tool may be dtfficidt to replicate if you need to haoe the same angle iine in ariother part of a drawing. Figure 13-20. Shifi-constraining the Line tool limits line angles to increments of fifteen degrees for easy replication in other parts of a drawing or other drawings. 2 18 HyperCard's Authoring Environment Chances are that you'll use the constrained Straight Line tool to draw horizontal and vertical lines most of the time, but there are also other ^ ■ ' occasions to use it, particularly with the angled lines. If you are creating - ^' ; a three-quarter- view image, you'll want to maintain the same angle for ' all lines that connect various planes of the drawing. Once you deter- - s mine which constrained an^e works best, you can recreate the .■ ' identical angle for the rest of the connecting lines in your drawing. OPTION KEY ENHANCEMENT . ^ - ; . t ! Black isn't the only ink your lines can be. You can also draw straight lines with any pattern In the Patterns palette (or pattern of your own design). To accomplish this, select a pattern from the palette and hold down the Option key before drawing your straight Une. Drawing straight lines with patterns takes experimentation to achieve tlie desired effect. As we'll see in more detail when we discuss patterns, the results of your patterned lines may not be as you expect because of the nature of pattern generation on the Macintosh screen. Essentially, the angle of the pattern does not change with the angle of the line: It's not like angling a wallpaper roll, as you might expect. So be prepared to try various patterns, particularly irregular patterns, before settling on one. Just hold down both the Option and Shift keys when starting to draw the straight line. One very practical application of Option key pattern drawing Is to draw white lines atop black or patterned areas. In card borders, for instance, you can select the all-white pattern and paint Shift-con- strained straight white lines as insets to heavy black borders of someone else's design (Figure 13-21 J. You might also try drawing with a grey pattern atop other patterns in the same manner. Figure J 3-21 . Using the Shift constrained. Option-enhanced Une tool lets you drau; straight-edged patterns (including the white pattern) in whatever thickness you select Jmm the line size dialog box. Above, two thicknesses ofwhiie lines ornament an otherwise dull border. HyperCard Painttng Palettes 219 The Spraypaint Tool - Even if you claim to have no artistic talent when using these HyperCaid painting tools, the Spraypaint tool will give you a sudden feeling of artistic power. With this tool, you can use any pattern in the palette to produce subtle gradations of shading on the screen. The metaphor of a spraypaint can is most apropos. Painting with a real can of spraypaint lets you apply varying textures of the paint, depending on how quickly you pass the nozzle over the surface and how many times you cover the same area. HyperCard's Spraypaint tool works in much the same way, with the added advantage that the "paint" doesn't run when you apply too heavy a coat in one spot. When you select the Spraypaint tool from the Tools palette, the cursor turns into a nozzle of sorts (Figure 13-22). The dots you see are where the paint comes from as you pass the cursor atop the graphics layer of your choice. As you can see, they're spread fairly far apart. If you simply click the Spraypaint cursor and quickly release, paint will come through whatever dots line up with black segments of the selected pattern. On a black pattern, all dots will issue paint; on a very thin grey pattern, only a few dots will likely splash paint onto the surface. Paint doesn't come through those dots in a steady stream. It pulses, albeit quickly. But if you drag the cursor along the surface very quickly, the pulsing action will leave definite blotches along the trail of the cursor, not connecting lines (Figure 13-23). Therefore, the speed at which you drag the Spraypaint cursor in the painting area greatly influences the thickness of coverage the pattern will have. Likewise, if you go over the area a second time, it is highly unlikely that the dots of the cursor will be in exactly the same spot. Therefore, you will get 1 1 1 1 1 1 O o A O a Figure 13-22. The Spraypaint tool uses a "nozzle" cursor to indicate the density of paint that pulses from it as you drag the tool. 220 HyperCard's Authoring Environment Fast Drag Slow Drag -M, Figure 13-23. Paint pulses from the Spraypaint nozzle as you drag the tool across the screen. Coverage on the screen is directly related to the speed at which you drag the tool additional coverage by the pattern on succeeding passes. The slower the pass, the greater the coverage. There is certainly no hard-and-fast rule about which patterns make the best paints for the Spraypaint tool. It's something you'll have to experiment with for each application. Surprisingly, some of the tex- tured patterns provide very nice effects when used in a light coat, just lighter than revealing the actual pattern. Therefore, don't be fooled into thinking that only black and grey patterns are for shading {Figure 13- SHIFT KEY ENHANCEMENT Constraining action is available for the Spraypaint tool. Holding down the Shift key prior to painting keeps the tool active in either the horizontal or vertical axis, depending on the direction of your very flrst Figure 13-24. Use the Spraypaint tool for shading effects you cannot get from filUr^ patterns. 24). HyperCard Painting Palettes 221 move with the tool. Typically, the Spraj^jalnt tool is used freehand, but there may be times when you want to constrain this tool. COMMAND KEY ENHANCEMENT ' f ' An unexpected property of the Spraypalnt tool comes to life when you hold down the Command key prior to painting. Instead of leaving a sprayed trail of a particular pattern, the tool erases whatever is beneath it, but in the same thin coverage as when the tool sprays paint. Therefore, you can work In the reverse of shading a white area with black. Start with a black area, like a circle, and start erasing "shades" of black until you make the circle appear as a sphere, complete with white highlights (Figure 13-25). The Rectangle Tool ^ ; \ 1 . . ; : . Painting rectangles in HyperCard Is a breeze. When you select the Rectangle tool from the Tools palette, the cursor becomes the cross pointer (the same as Straight Line tool). Place the cursor on the screen where the upper left comer of the rectangle is to appear. Then drag the cursor to the right and down, TTie outline of the rectangle expands as you drag the bottom right comer. When you've placed the bottom comer where you want it, release the mouse button. Remember that because this Is a bit-mapped graphics environment (instead of an object-oriented one), the "rectangleness" of the shape is only in the eye of the beholder. HyperCard sees It only as a series of black pixels on the screen. You won't be able to resize a rectangle once it is drawn. If you make a mistake, undo it and try again. Figure 13-25. Gradations qfshadir\g on a dark object can be achieved with the Command-key enhancement to the Spraypalnt tool 222 HyperCard's Authoring Environment You do, however, have control over several properties of a rectangle: The thickness of the border line, the presence or absence of a fill pattern (and what that pattern will be), whether the border should be a black line or the same as the fill pattern, whether the rectangle should be drawn as a perfect square, and whether the rectangle should be drawn from comer to comer or around a specific center point. When you start up the HyperCard painting tools, the standard . ; ' setUngs for a rectangle specify a black border of one pixel in width, no ( • fill pattern, and drawing from comer to comer when you drag its outline with the rectangle tool cursor. If you change the thickness of the border ■i ■- line, the tool's cursor takes on a size commensurate with the line thickness. This property has nothing to do with the type of ink used to draw the border, merely its thickness. DOUBLE-CLICK SHORTCUT While it is always possible to fill a rectangle with a pattern at a later time (see the Paint Bucket tool , below) . you can also draw it right away with a pattern. There is a menu option to turn on painting filled images, but the shortcut is to turn this setting on by double-clicking the rectangle tool in the Tools palette. When you do this, the rectangle in the palette ^ . ^ turns grey, indicating that the filling option is tumed on . That grey does . not represent the pattern it will be filled with. The actual pattern is determined by the selection In the Patterns palette. Now when you draw the rectangle on the screen, it automatically draws filled with the ; selected pattem. You can't change a pattem once it fills a rectangle, so i , if you don't like the results, undo it, and try drawing the rectangle again . , , with a different pattem. If you can't find one right away that does the job, paint the rectangle without a fill pattem and experiment later with patterns and the Paint Bucket (below), once all the other elements In the graphic are set. OPTION KEY EJMHANCEMENT In some designs, the black border of the standard rectangle may interfere with the look you're attempting. The most common example would be a preference for a dotted line Instead of a solid black line for a rectangle border. That's a perfectly normal request. And HyperCard will accommodate it with the Option key. When you hold down the Option key prior to dragging a rectangle, the j tool draws the rectangle with a border made from the current pattem selected in the Patterns palette. To make a dotted line border, for , ., , , Instance, you would select one of the grey pattems in the palette and then draw the rectangle with the Option key in force (Figure 13-26), Because of the way HyperCard draws pattems on the screen, the result HyperCard PainOry Palettes 223 liiiiiiil r — T t 1 >? "a m o A O mmmmm mmm^ Figure 13-26. With the Option key pressed, the Rectangle tool draws the outline with the currently selected pattern. rt -ix^i may not always meet the expectation, particularly with the more irregular patterns in the palette. Be prepared to experiment a bit until you find the right combination. With some patterns, for Instance, you may have to select a thicker line to make the border be seen with any regularity around the perimeter of tlie rectangle. Keep this enhancement in mind when you wish to draw a kind of filled patch on the screen with the appearance of no border. What you'd do is draw a filled rectangle with the Option key held down. The result is a rectangle bordered by the same paint pattern as the Internal fill (Figure 13-27). SHIFT KEY ENHANCEMENT ^''^ ' '^'^r - Unless you have an excellent eye at the 72-dpi resolution of the Macintosh screen, you'll be hard pressed to drag a rectangle that is a perfect square, if that Is your goal. To help you in this regard, the Shift Figure 1 3-27. With the Option key pressed and Draw Filled selected, you get the effect qfa borderless rectangle, althoi^h the border is being drawn with the same pattern as the filled center. 224 HyperCard's AutJwring Environment key constrains rectangles into perfect squares. Use the Shift key along with fill patterns and the OpUon key when you wish to create squares with the pattern border or "borderless" properties we Just described for all rectangles. The last rectangle property under your control is the ability to draw the rectangle from its center point. That is, instead of drawing a new rectangle from one comer to its opposite, you place the cursor at the center point of the rectangle and drag the cursor out from the center. This is particularly helpful when you are building a series of concentric objects {this property works with HyperCard's other drawn objects, like rounded rectangles, ovals, and polygons). To turn on this feature, choose Draw Centered from the Options ' ' menu. A checkmark will appear next to this menu item when it is in force. ' One way to put this feature to use is to first establish a center point in the area where the concentric shapes are to be. Click the pencil tool ,5 . . there once to designate one pixel as tlie center point, Just as you might ,, on a piece of paper. Then place the drawing cursor atop that point. The , . centerpoint of the cross will turn white when it is atop the pixel (Figure 13-28). Then drag the cursor away from the centerpoint until the shape , = Is the desired size. Repeat this procedure for each of the shapes, even , , if they have different border thicknesses [Figure 13-29). The Rounded Rectangle Tool Every property we discussed for rectangles applies to rounded rec- tangles, including all shortcuts and enhancements. Therefore, we won't repeat them here. Rounded rectangles are often preferred for such things as HjperCard , backgrotmd designs. Their appearance is less harsh than a regular ■■ rectangle (Figure 13-30). The roundness of the comers may be too much for certain graphics applications, however. In small rectangles or squares, you may prefer to draw a regular rectangle shape and modify the comers slightly with FatBits (demonstrated below) rather than use the level of rounding the Rounded Rectangle tool provides. The Paint Bucket Tool After using the HyperCard painting tools for a while, you'll come to think that the Paint Bucket is the most powerful tool in the palette. With one click of the mouse, you can instantaneously influence the appear- HyperCard Painting Palettes 225 I ii y Centerpoint turns white Cursor Figure 13-28. To draw concentric shapes, establish a centerpoint with one dot. Then plaee the cross cwsor directly above the dot before dragging each shape. The center spot of the cross cursor turns white when tt is directly above the centerpoint dot. ? , ' . , / ;r ; ■ Figure 13-29. You can use the same centerpoint to draw different kinds of concentric shapes. Figure 13-30. Rounded rectangles (right) are often preferred over regular rectangles (left} becanse of their softer look. 226 HyperCard's Authoring Enuironment ance of a huge area of the screen— or the whole screen, if you're not careful. Hie primcuy purpose of t±ie Paint Bucket is to fill outlined areas with whatever pattern is selected In the Patterns palette. The key phrase here Is "outlined areas." What we mean is that to contain the spread of the paint from the paint bucket, the area must have a solid border around it. If one ptsel is missing from the border, paint wlU "ooze" out and contaminate areas outside the outline. Fortunately, you can undo your mistakes, so no permanent damage Is likely to occur (and not one drop of turpentine is needed) . Clicking on the Paint Bucket tool causes the cursor to turn into the very same bucket as in the palette. It's important to understand the most Important aspect of that bucket: the point from which the paint spiUs onto your graphic. The bucket cursor's "hot spot" Is one pixel below the tip of the pamt that appears to be spilling out of the bucket (Figure 13-31). When you're working in close quarters on the screen, this is the spot of the cursor that you want to be located Inside the outlined area before clicking the mouse button to fill with the pattem. When paint oozes out from what you thought was a solidly outlined area, it's time to closely inspect the outline. Before you do anything, however, be sure to undo the ooze. Then invoke FatBlts (explained in more detail in chapter 15) and scroll around the entire outline. Look for the smallest gap. Figure 13-32 shows valid outlines and samples of tricky gaps to help you spot trouble. These gaps can happen for any number of reasons when creating or editing shapes with the HyperCard painting tools. While an unaltered rectangle should not have any gaps, certain stretches of an oval and odd-angled lines can easily have multiple gaps as HyperCard tries to paint a best fit on the screen. Don't be alarmed by gaps. Simply find them and plug them to the best of your ability. Then It's Paint Bucket time. ... - 'Hot Spot' Figure 1 3-3 1 . The Paint Bucket tool's "hot spot' is where the paint pours fiom, ]. HyperCard Pamting Palettes 227 Gaps - Invalid Containers nn ■ ■ ■ ■ ■ ■ ■■■■■■■■■■ ■ ■ ■ ■ Figure 1 3-32. Closeups of valid and invalid outlines that contain and ooze Patnt Bucket paint, respectively. The Paint Bucket has another property that might not be self-evident, given Its definition above. When you apply the Paint Bucket to a shape that may be filled with another pattern or all black, you can alter the appearance of the pattern— provided there is the equivalent of a solid outline around the area. In an all-black square, for example, you can touch the paint bucket to any place in the square and it will change Into the pattern selected in the Patterns palette (Figure 13-33). The pattern extends only as far as the outer edge of the square, which the tool Interprets as being the solid outline. One application of this technique is to change painted text (see below) from its regular black into a pattern, perhaps a grey "Ink." To make this happen, you type the text in the desired font and font size. Then select the Paint Bucket and a pattern. Carefully touch the hot spot of the paint bucket cursor to each letter in the text (Figure 13-34). It may take a while if the text Is extensive, but the result will be striking, depending on the font, font size, and pattern chosen. Experiment with this feature. DOUBLE-CLICK SHORTCUT The Paint Bucket tool offers a most convenient shortcut in anticipation of your desire to change the selection In the Patterns palette. Double- click on the Paint Bucket tool in the Tools palette and the Patterns palette automatically appears, already detached from the menubar. 228 HyperCard 's Authoring Environment Figure 13-33. Use the Paint Bucket tocHange bkuckobjects topattemedobjects. ; - Arma viru^que cano Figure 1 3-34. By touching the Paint Bucket tool to painted text, you can turn the i - : ■ text characters into a pattern selected in the Patterns palette. Double-click a second time to hide the palette (or close the palette by clicking on its close box). The Oval Tool a>i . ;-, Sometimes it seems that ovals and circles are the hardest regular , , shapes to draw on paper, even with the help of compasses and templates. Not so with HyperCard's painting tools. They're as easy to draw as rectangles. In fact, all of the enhancements and shortcuts that apply to rectangles apply to ovals. With the Oval tool, the shape may be (. different, but the concepts are the same. Therefore, constraining with ■i the Shift key produces perfect circles with the Oval tool, just as it , produces perfect squares with the Rectangle tool. Because of the • consistency of these enhancements and shortcuts, we refer you to the HyperCard Painting Palettes 229 rectangle discussion for details. If you're already familiar with the properties of rectangles, you already know ovals inside and out. About the only property of ovals you should be aware of is that they may leave gaps in their outlines, wreaking havoc with the Paint Bucket tool. Of course, if you draw the oval (or circle) with the Draw Filled choice in the Options menu turned on, HyperCard wUl hold the pattern within the confines of the outline, even if there is a gap In It (Figure 13- 35). Concentric circles of the same or varying line thicknesses are effects ■ you may wish to try. Just use a center point and choose Draw Centered from the Options menu. Trying this effect without the benefit of the Draw Centered option can be a frustrating endeavor. If you need a semicircle as part of a drawing, use the Oval tool to draw the entire circle. Then erase the half you don't need. The coffee cup in the HyperCard help system's description of ovals is an excellent example of what you can do with ovals and semicircles both shaded and hollow. Study this picture on your HyperCard screen and try to replicate it on your own. You'll learn quite a lot from this one picture. Figure 13-35. Ovals may leave gaps in their outlines when stretched to extreme proportions. If you. draw a JlUed otxil, however, the pattern remains within the border, even if gaps appear. Option-dragging creates a border with the same pattern as the JlU pattern, as if no border existed. 230 HyperCard's Authoring Environment TheCurveTool . -^..^^ " '■ v A j . J ' . ",1 i ■- The Curve tool is peihaps inappropriately named, since it is more of a freehand drawing tool with a hybrid set of properties from the pencil and other shape tools. From the pencil comes the ability to draw any 1 ! freehand shape you wish. From the other shape tools comes the ability to draw with a thicker line, draw with a pattern as the ink, and, optionally, to have the tool automatically fill with a pattern whatever . ' area the freehand shape encloses. Let's see how these various proper- ' . V J. ties work, ' ui First, well look at the Curve tool's raw drawing ability. When you select the Curve tool, the cursor changes into the same cross that draws i : other shapes (Figure 13-36). The center of the crx)ss is the point from , which the "Ink" Hows as you drag the cursor around the screen. You are free to drag it in any direction and to the maximum of your skill in this department. If you change the thickness of the line, the cross cursor changes thickness to match. This is consistent vrith the behavior of the shape- drawing tools. OPTION KEY ENHANCEMENT . With the Option key pressed, the "ink" of the line left by the cursor becomes the pattern currently selected in the Patterns palette. This behavior, too. Is consistent vrith what you've learned for other shape tools. There is no need for a Shift key constrain action with this tool. At most, it would give you the ability to draw a soUd or patterned line in iiDii;i!i;=i!f=i;;[!iiiiiiiE[ r — T i 1 1 1 o i A + Figure 13-36. The Curve tool uses the cross cursor shared by most tools. HyperCard Painting Palettes 231 the vertical or horizontal axis. You've already seen how to do that with the Straight Line tool. DOUBLE-CLICK SHORTCUT As with the other shape tools, when you double-click on the Curve tool, it turns on the Draw Filled option In the Options menu. You might wonder, though, how the tool can possibly draw a filled shape when the shapes this tool creates are so freeform. The answer lies In a special feature of the Curve tool that is in effect when the Draw Filled option is In force. The tool automatically draws the line that connects the start and end points of your drawing and then fills the enclosed area with the selected pattern (Figure 13-37). As far as the automatic closing up of the loop Is concerned, it follows the same principles used by the Lasso as it finishes the job for you. Therefore, it's up to you if you wish to try to bring the drawn line all the way back to the starting point or let the tool finish it. You can combine the Draw Filled choice with the Option key enhancement to draw custom filled shapes with what appears to be no border. Actually, the border is in the same pattern as the internal fill (Figure 13-38). This tool is fun to experiment with, because you can create rather complex shapes and observe how HyperCard fills the nooks and crannies according to Its rules about filling to the outline. (a) ' Cb) - Figure 13-37. Drawing ajilled curve means that HyperCard automatlcaUy doses the gap between the start and end points of the curve andJVls the area inside. 232 HyperCard's Authoring Environment - > Figure 13-38. Drawirig JUled and with the Option key creates the appearatwe ; of borderless shapes, some of which may surprise you. The Text Tool .^j'-', ''^r^ ^''P ^'A .s'^" The kind of text we'll be discussing here has no relation to the text that goes inside text fields— the information that cards hold. This text is the kind that goes into the background or card picture layer and can be ' . . ; altered only with the painting tools . You'll use painted text primarily in the background graphics layer as card headlines and as labels for text fields you or the browser will fill with Information. The text will appear ■ ^ ' on all cards sharing that background. Clicking on the Text tool in the palette— make sure you differentiate this in your mind from the Field tool in the upper right comer of the palette— causes the cursor to change into an I-Beam cursor. To use the default font and font size (Geneva 12), simply click the text pointer on the screen where you wish to begin placing text. Then start typing. You may make multUined text by pressing Return at the end of a line (Figure 13-39). Graphics text may be placed in the background or card domains. Figure 1 3-39. Create multilined graphics text by pressing Return at the end of a line. HyperCard Painting Palettes 233 DOUBLE-CLICK SHORTCUT Text may be typed in any font installed in your System File. To change the font attributes of text prior to typing the text, either choose Text Style from the Edit menu or, more conveniently, double-click on the palette's Text tool icon. Either way, you'll get the font dialog box (Figure 13^0). It's the same font dialog that you get with the Field tool {chapter 9), so there's no need to spend more time on it here. There is one very important difference between text in the paint layer and in fields if you or your browsers plan to print cards from your stack on the LaserWriter. Text in fields will be sent to the printer as separate characters that are turned into laser fonts, like Helvetica and Times. Print quality of that text will be very good- as good as a LaserWriter user ejqDects from text. Paint layer text, however, is not sent to the I^ser- Writer as separate text characters for translation into laser fonts. Paint text goes to the printer as a bit map, just like the boxes and drawings In the paint layers. If the user prints the card without checking Smoothing on the HyperCard's Page Setup dialog box, then the paint text will be printed with the same resolution as displayed on the screen. If, on the other hand, the user prints with Smoothing in force, the LaserWriter will do its best to smooth over the bumps of the text characters, but it will not print them with the clarity of laser fonts. In fact, sometimes smoothing Style □ Bold □ Italic □ Underline □ Outline n Shadow □ Condense □ EHtend Rlign ® Left O Center O Right Cairo o Chicago Courier Geneua Heluetica Monaco Hos Eisleg Neiii Vork Sgmbol Times , . o 9 o 10 12 14 18 20 24 o [cancel ] Line Height 24 Sample Figure 13-40. Font dialog box 234 HyperCard's Authoring Environment does an injustice to a nicely designed screen font. We also recommend that you choose Precision Bitmap Alignment in the LaserWriter's Page Setup Options screen to reduce possible distortion. Believe it or not, there is a good side to this loss of laser resolution on paint layer text. You can use any screen font you like in designing paint layer text without worrying about the browser having the same fonts Installed on his Macintosh System File (a concern with text in text fields) . This is because, just like shapes, the text characters essentially lose their identity once they are typed onto the paint layer: They become simply a layout of pixels In what we recognize as text. Therefore, if you find a public domain font or purchase one that looks particularly good for your stack design, you have the confidence that what you design on your screen will be there when browsers from all walks of System File life start using your stack. • ; While you're typing text Into the paint layer, it stays in a somewhat active mode until you click the mouse elsewhere. Until you cbck the mouse, however, you can still adjust the font characteristics of the text you just tj^ed. Therefore, select the Text tool, plant the text pointer on ■ the card where you want text to begin , and start tjrping. Before you click anywhere else on the card or on any other tool, double -click on the Text tool to bring up the font dialog box. The current settings for the text you Just typed will be highlighted. Change any settings you wish and click OK. The changes will be made to the text. Even now, you can go back and make additional changes to the font attributes. One thing you may not do to text you type into the paint layer is edit it like you do text in a field. In other words. If you notice you made a mistake in a word earlier in the sentence you're now typing, the only way you can go back to make a correction is to backspace to the error and continue on from there. If you try to select the text with the text pointer, you will commit the text that you typed to pixels on the paint layer, and shut yourself off from adjusting any part of its text or font attributes. This aspect may take some getting used to. But that's why Undo exists. COMMAND AND SHIFT KEY SHORTCUTS A problem with using the Font dialog box to adjust text after you've typed it in Is that the box covers the whole screen. Once the box disappears, you have a hard time Judging the effect of the change you \ specified. Font changes are often subtle. You can, however, adjust the i . font and font size from the keyboard without calling up the font dialog box. First of all, it's important to understand that you can do this only while you are entering text or after you've entered the whole chunk of HyperCard Painttrig Palettes 235 text but before you've clicked the mouse button anywhere. In other words, the text must be sitting there ready for you to type in more text if you have any. When you're at that stage and ready to experiment with font and font size, hold down the Command key while pressing the comma and period keys {it may be easier to think of these keys as the < and > keys). With the Command key down, these keys adjust the size of the font of that active text to the sizes of that font Installed in your System File. If you typed the text originally in Geneva 12, pressing Command-< twice will bring the text down to Geneva 9. From there, you can press Command-> three times to bring the text up to Geneva 14. Remember, the sizes available in this shortcut are only those installed on your System. Therefore, if you typed the text in Chicago, these two Com- mand-key shortcuts will not change the text In any way, since only Chicago 12 is installed on most Systems. By holding down both the Command and Shift keys, you can try other fonts installed in your system on the current text. Type Command- Shlfl-< to try a font whose name is earlier in the alphabet than the current font; type Command-Shift-> for a font whose name is later in the alphabet. What is going on here is that each press of the magic keyboard combination shifts the selected font one slot in the corre- sponding direction up and down the list of fonts in the Font dialog box. Because fonts are listed alphabetically in this dialog, that's how they change when you press the Command-Shift combination. You can use these two shortcuts together to find the right font and size for a piece of text you are putting into the graphics layer. Type it first in the default font. Use the Command -Shift combination to try different fonts. When you find an acceptable font, use the Command- key shortcut to try different sizes in that font. This system turns out to be an efficient way of selecting the right font for each graphics layer text Job. TEXT STRATEGIES ^ - ^ \ : Rilf' ' ^ j :? ^ Choosing fonts for the background, card, and field layers should be taken seriously. Newcomers to the Macintosh often get so caught up in the flexibility of offering many fonts that screens (and even word processing documents) become cluttered with too many fonts. Hiere is rarely reason to use more than three fonts on the same card. If more are used, the font potpourri may distract the user from the information content. Remember that readability of the information should be your first priority. There are many techniques for entering paint text and manipulating it on the screen. Chances are that you'll find it easier to type paint text 236 HyperCard's Authoring Environment in an open area on the screen and then select it like any image and move / ; it into the precise position you choose. That's a fine strategy, and often an efficient one. If you find that you need to piece together a line of text from disparate , J pieces or make sure corresponding lines in multiple columns are on the : - same horizontal base line, you can use the Straight Line tool to help. First position the starting piece of text on the screen. Then select and drag the next piece as closely into position as your eye will allow (Figure 13^1). Next, select the Straight Line tool and draw a constrained horizontal line to create an artificial base line for the text (Figure 13- , 42). Compare how the first and second chunks of text look with respect to the base line. If the second chunk is too high or low, estimate how many pixels (it will probably be just one or two) and immediately undo the straight line. Select the second chunk of text and drag it the appropriate distance. Repeat the straight line trick until both chunks of text are on the same horizontal. The Regular Polygon Tool ' The Regular Polygon tool is so much fun that you'll catch yourself playing with it for long stretches, trying to grasp all its potential. We'll only scratch the surface in this discussion. Experienced MacPaint users should also pay close attention, because this tool is new. A polygon is a shape with many ("poly") sides. A regular polygon is a polygon all of whose sides are of an equal length. The number of sides is unspecified. It can be anywhere from two to infinity. In HyperCard, a regular polygon can have three, four, five, six, eight, or infinity sides. In geometric terms, these shapes are the isosceles triangle, square, pentagon, hexagon, octagon, and circle, respectively. Text chunk 1 €uKcf^)iCy. Figure 13-41. To align different groups of text, bring them into position as weU as you can. Text chunk 1 and chunk 2 |_ Figure 13-42. Then draw a temporary baseline to see if the two text chunks are on the same horizontal Immediately Undo the line and make atyustments to teid groups as needed. Repeat the temporary line to make sure all text is aligned. HyperCard Painting Palettes 237 A special feature about regular polygons in HyperCard Is that you can rotate them as you create them. When you select the Regular Polygon tool from the Tools palette, the cursor becomes the now-familiar cross cursor. You click on the location on the screen where you want the centerpoint of the polygon to be. As you drag the cursor away from the centerpolnt, the polygon grows and is free to rotate to follow the cursor as you control it with the mouse (Figure 13-43). SHIFT KEY ENHANCEMENT Rotation can be constrained to 15-degree increments when you start creating a regular polygon with the Shift key held down. Depending on the number of sides the polygon has, this constraint may help you choose an orientation of the polygon that best displays each side's straight lines with the least amount of distortion. Note that when you rotate a polygon, its border line may have one or more gaps that must be plugged before you can fill the area with the Paint Bucket tool. The alternative is to draw the polygon filled from the start, as noted below. DOUBLE-CLICK SHORTCUT When you select the Regular Polygon tool, HyperCard automaUcally preselects the square shape for you. To choose one of the other shapes, you can choose Polygon Sides from the Options menu or, more conveniently, double-click on the Regular Polygon tool in the Tools palette. ,r>h/ I' . ! i Figure 13-43. Regular polygons are always draggedfrom their centerpoints and can be rotated freely unta you are satisfed with their orientation. 238 HyperCard's Authoring Environment ADO Figure 13-44. Regular Polygon dialog box. In return, you see a dialog box featuring outlines of all six polygon shapes offered by HyperCard (Figure 1 3-44) . A small box surrounds the ■ current selection. To choose another shape, click the mouse pointer on ' "' ■ •■ • it. The dialog box disappears, and that shape can now be drawn with the Regular Polygon tool. The thickness of the border may be altered by changing the line- thickness choice in the line size dialog box. As you've come to expect of ' tools that offer vaiylng border line thickness, the cross cursor of the regular polygon tool thickens with the selected line thickness. OPTION KEY ENHANCEMENTS Similarly, you can draw the border with a pattern by holding down the Option key Just prior to drawing the polygon. The border pattern will be ' ^ in the thickness specified by the line size. If you wish the polygon to be drawn initially with a pattern fill, choose . Draw FiUed from the Options menu and select a pattern in the Patterns palette. With this menu Item turned on, you can draw the polygon with what appears to be no border when the Option key is also pressed, since the border of the shape and its filled pattern are identical. Regular polygons, probably more than any other shape in the Tools palette, benefit from an option we haven't yet said much about: Draw Multiple. This feature lets you draw repeated Images of a polygon automatically. Combining repeated images and the polygon's ability to rotate can make for some remarkable images that don't require a great deal of artistic skill (Figure 13-45). You can turn on Draw Multiple by typing Option-M. Moreover, you can set the frequency with which images are repeated j as you rotate or grow the polygon. By also typing the Option key and a i digit from 1 to 9 (as a rule, use the top row of keys Instead of the numeric keypad), you specify the spacing between images. The smaller the number, the denser the repetition; the higher the number, the more j widely spaced the repeated images are. If you then hold down the j o] o o HyperCard Painting Palettes 239 Figure 13-45. The Regular Polygon tool makes it easy to draw rather complex drawings. , . ,. ,^ Option key when drawing the polygon, the repetitions are of a polygon whose border is of the same "ink" as the currently selected pattern. What this all comes down to is a vast variety of possibilities using the Regular Polygon tool. As a starter, study closely the examples In the HyperCard help system that demonstrate examples of regular polygons (shown in Figure 13-46). Then plan to spend time experimenting with the combinations of various settings. You might even want to create a stack of polygon Ideas that you've created. Do all your drawing in the card graphics layer of the stack and conduct one experiment on each card in the stack. Set up a background text field, as well, to make room for notes that wOl remind you about which settings were in effect when the sample polygon effect was made. Then you'll have a record of your experiments for use later on, when creating yet other stacks. 240 HyperCard's Authoring Environment o ill 1 1 □ o o Regular Polygons Double -click to specify the number of sides the polygon should have. The polygon is centered wh&re you start dragging. Press Option -M to draw multicopied polygons. | Use the Shift key to constrain one side of the polygon to 15* increments. Mul"ti Option-4 Figure 13-46. Examples of regular polygons from the HyperCard Help system The Irregular Polygon Tool The last painting tool In the palette lets you create irregular polygons on the screen. An irregular polygon is a many-sided object whose sides are not necessarily of equal length. Elach side, howevei: is a straight line, no matter how long or short. Uke most of the other shapes, you can draw irregular polygons with borders of varying thickness. When you draw the shape, however, the • ' behavior of the lines you draw will seem very different. First you position the cross-hair cursor at the begirming point of the polygon with ' ' ■ ■ a click. You may then release the mouse button, but the tool is not only still active, it stretches the first side of the polygon from the starting H« ■;, point, like a rubber band. You determine the second pohnt of the ■ 'm. polygon and click the mouse button. Again, the second side stretches ' ^ between the second point and the cross-hair cursor. You keep up this ' •' ' plant-and-stretch process for as many sides as your polygon needs «• (Figure 13^71. One way to close offthe polygon is to click the final point on the same point as the starting point. Another way is to click a point twice on the • ■ same pixel. This halts the polygon drawing (this is good to remember If you find yourself getting carried away and unable to find the starting point). HyperCard Painting Pcdettes 241 Figure 13-47. Irregular polygons are defined by stretching each side, clicking where the side ends, and stretching the next side. A double-click at any point ends the polygon definition. OPTION KEY ENHANCEMENT To draw an irregular polygon with a pattern border rather than black, hold down the Option key when you click the starting point of the polygon. You may release the Option key after that, whUe you carefully position each point of the polygon. SHIFT KEY ENHANCEMENT ' You can constrain the angle of each side of an irregular polygon to multiples of 1 5 degrees by starting the polygon with the Shift key down. This choice tends to make more polished polygons, but you'll have to evaluate the look and how It compares with the graphics concept you're striving for. Holding down both the Option and Shift keys when starting the polygon gives you 15-degree constraint of patterned border lines. DOUBLE-CLICK SHORTCUT Irregular polygons can also be automatically filled upon completion, if you like. The Draw Filled option (in the Options menu) can be turned on by double-clicking the Irregular Polygon tool icon in the Tools palette. When you close up the polygon, the tool fills the area within the border with the currently selected pattern. If instead you double-click on one pixel, thus ending the polygon creation process, the tool will draw a line between that doubleclick point and the starting point of the polygon. Then it will fill the interior with the selected pattern (Figure 1 3- 48). This behavior is consistent with the filling that the curve tool performs. If you are unsure about a particular pattern prior to building an irregular polygon, draw it without a fill pattern and use the Paint Bucket to fill it later. Be on the lookout, however, for sides of the polygon 242 HyperCard's Authoring Environment . (a) (b) (c) Figure 13-48. If you end the polygon definition while drawingJUled, HyperCard autoTTUiticcdly closes the gap between start and end points, JUUng the interior with the currently selected pattern. that may have gaps because of odd angles. If paint oozes out of the ■J ' polygon, undo the damage, and plug the gap(s) with FatBits (described ''i.' ^ In chapter 15). The Patterns Palette By now you've seen that the Patterns palette may be torn from the menubar just like the Tools palette. You may also show the Patterns , palette (already detached) by pressing the Tab key whenever you're in the printing tools. Figure 13-49. The Patterns palette HyperCard Painting Palettes 243 HyperCard comes with forty predefined patterns. The Patterns pal- ette displays small samples of them. When you first select a paint tool, HyperCard preselects all-black as the pattern. A selected pattern has a white border around It in the palette (Figure 13-49]. To select a different pattern, click on the sample in the palette. DOUBLE-CUCK SHORTCUT ; ^ ^ : You are free to edit any pattern In the palette. While you can reach the pattern editing facility via the Options menu, you may also double-click on a pattern In the palette to reach the editing facility. See the discussion about the Edit Pattern choice in chapter 15 for complete details about patterns and pattern editing. That wraps up the detailed discussion of the painting tools and palettes. But there is a lot more to the HyperCard painting environment than Just those tools. Next, we'll dive Into the selections on the Paint menu. CHAPTER 14 The Paint Menu In our introduction to the painting tools, we drew a distinction between the bit-mapped characteristics of paintlike graphics environments and object-oriented environments of the MacDraw variety. The graphics environment of HyperCard is bit- mapped, but some of the features we're about to show you may make you wonder if HyperCard doesn't have a bit of the object orientation in its graphics tools. What is really going on is that HyperCard devotes a portion of the Macintosh's memory to monitoring the things you draw on the screen. Every time you click the mouse to drag a new rectangle, rotate a new polygon, or type some paint text, the program stores the steps you went through. It laiows which was the most recent "thing" you painted on the screen. But what it can do with this knowledge is exciting. It can select the shape or text— even if it consists of a complex pattern-filled shape atop a previously painted shape with yet a different pattern. You get the feeling that the last item you drew on the screen is in a kind of middle ground between bit-mapped shape and drawn object: not quite in the real bit map of the graphics layer you're working on, but hovering perilously close. That may not be a bad way to think about the most recently drawn shape. You need to remember that the last shape Is always available for instant selecUon or modification by many Paint menu selections. The instant you cHck the mouse to draw another shape, the previous one is fixed into the bit map of the graphics layer. If you're new to painting programs, this shouldn't be too difElcuIt a concept. For MacPaint users, it's a whole new ball game. 245 246 HyperCard's Authoring Environment With this understanding, we can now progress down the Paint menu to see what goodies lie in store for HyperCard authors working on the graphics layers. All these features work in both the background and card graphics layers, but most of the time, you'll be working in the wm-^i,.- background graphics layer to create consistent card environments throughout a stack. ■ " "s - f ? ' Select You'll recall the discussions we had when looking at the actions of the Selection and Lasso tools in the Tools palette. The point of selecting any piece of graphics is to alert HyperCaid which pixels we want some action to work on, whether it be as simple as moving the item around the screen or as complex as rotating it. It turns out that a majority (not all, to be sure, but a majorily nonetheless) of the actions we want to perform on a shape occur Immediately after creating that shape. This is one reason HyperCard takes great pains to remember the last shape (including paint text) we draw on the screen. Rather than messing with the Selection tool or V . Lasso, we can tell HyperCard with the Select command to select the ■ „ item just painted on the screen. When we issue the Select command, the "thing" we just added to the screen is selected as if we had lassoed it. In other words, the marquee , ■ , . "hugs" the perimeter of the shape . We are now free to do whatever we'd normally do with a selected section of graphic. Select All ■ ' " ' " ;; 0 i ;<■■ When you want to capture the entire graphics layer— every pixel of the >-:^- 512 by 342 HyperCard window— Select All is the command for you. It ! is the same as dragging the selection rectangle from one comer to the opposite comer. The primary reason this command exists is that, with HyperCard • • graphics running under the menubar of built-in Macintosh screens, it is sometimes not easy to determine if dragging the selection rectangle from, say, the bottom left to the top right comers encompassed every pbcel. Select All removes any doubt. Be aware that this command works on the graphics layer only. It does i not select field or button objects. If you want to pick up all those Items for pasting Into another stack, for example, use the Copy Card option ' In the Edit menu when the painting tools are not in force. The Paint Menu 247 Once you've selected the entire graphics layer, you can copy it Into the cupboard for pasting elsewhere: In a clean, new background layer of a stack, for Instance. If you're building a new stack with a background Imported this way, you'll then have to start creating fields and buttons to give the cards some Me. While the Paint Bucket tool fills the area within an outline, the Fill command on the Paint menu fills the entire shape that is selected or that was the last Item drawn. As usual, the pattern this command uses is the currently selected pattern in the Patterns palette. Use Fill with caution, particularly on shapes that contain internal detail. If, for example, you lasso the rectan^e with the detail graphic shown In Figure 14-1 and then Fill it, the pattern will write over the detail graphic inside. If you Intended another effect, then don't use Fill for this task. Undo a Fill as you would any errant paint command. Invert The Invert command turns black pixels into white and white pixels into black within the area of the selection (Figure 14-2). This is a most practical tool for the design of certain shapes. It is sometimes easier to draw with a black pen and then invert the drawing to produce a white shape on a black background. Inverting can sometimes be tricky when the area you've selected for inversion is surrounded by a black line. The results of the inversion will vary, depending on whether you've selected the black line or an area one pixel inside the outermost black line. In Figure 14-3a, the selection is one pixel outside the border. In Figure 14-3b, the selection is on the Figwe 1 4-1 . Use FW. with caution, since it may overwrite a detail graphic within a selection. . ■, . - 248 HyperCard's Authoring Environment U border. Notice that inversion worked on all pixels inside and under the selection rectangle. Because the outer border of the graphic in Figure • 14-3g was not selected, it was not Inverted, whereas the white lines !<:- under the selection rectangle were. The result is a doubly thick black border. In Figure 14-3d, only the original outer black Une remains. The border is one pixel farther out from the center than Figure 14-3b. Figure 14-2. Invert turns black pixels to white, and vice versa, within the selection. Ca) To Dof To Dof To Dof (b) To Dof . •'"-it' ' ■ !! .-It (c) To Dof OS (d) To Dof To Dof To Dof To Dof To Dof Figure 14-3. Exercise care whenplacing tlie selection rectangle around an area to be inverted. Invert affects all pixels ivithin and under the selection rectangk. The Paint Menu 249 Pickup The Pickup concept may be a bit difficult to grasp at first, but it turns out to be a powerful tool in a bit -mapped graphics environment like HyperCard. In essence, it allows you to pick up a copy of an existing graphic in thie shape of a selected object (or the last shape you drew). One of the best ways to demonstrate this feature is to establish a scenario In which you have a detailed piece of art— perhaps from a commercial clip-art file— from which you would Hke to snip out an oval- shaped area for use in another card. Without the Pickup tool, you'd have to copy a rectangular section of the art and paste it into a new card for some painstaking erasure to leave the oval shape. The Pickup tool makes achieving your goal much easier. First you bring into view the clip art from which you want to copy. Then with a solid-filled oval tool, draw the oval on top of the area you wish to copy (Figure 14-4). Remember that until you chck the mouse someplace else in the graphics area, the oval is not quite on the same layer as the clip-art graphic, so the oval has not obliterated the original art. Now choose Pickup from the Paint menu. The oval has picked up a copy of the clip art and is selected. You can now cut it into the Clipboard. Use HyperCard's navigation tools to get to the new stack you're building and paste the picture into it. You'll get the oval tracing of the original clip art (Figure 14-5). There are many other uses for this tool. In the HyperCard help system, there is a suggestion about using it to trace text from an irregular pattern. That's a good one. Other ideas will come when you discover a need for complex outline shapes of complex drawings or patterns. Figure 14-4. To pick up an oval section of the graphic, first draw aJRled oual atop tlw desired area. 250 HyperCard's Authoring Enuironnient Figure 14-5. Wheri you choose Pickupfrorri the PatritTrierm (or type the P Power Key), the JiUed oval picks up the underlying graphic in the oval's shape. You con ' then drag, cut, copy, or paste the oval section wherever you need it Darken and Lighten We'll discuss these together because they do the opposite of each othec Both tools can be helpful In creating shading effects in carefully defined areas on the screen. If you were to drag the selection rectangle around a blank area on a graphics layer and choose Darken from the Paint menu repeatedly, HyperCard would gradually fill In the area with black pixels on a random basis (Figure 14-6). You could reverse the process by choosing Lighten repeatedly. This command turns random black pixels into white pixels within the selected area. You need not limit the affected area to a rectangle defined by the selection rectangle. Remember that all the commands in this menu work on the last "thing" drawn on the screen. That goes for ovals, regular and Irregular polygons, free- form curves, and text. Depending on the resulting look you're in search of, the random "pattern" created by Darken and Lighten may be more desirable in some places than the very regular patterns that come from the Patterns palette. The Paint Menu 251 (a) Cb) (c) (d) Figure 14-6. Darken fills the selected area with black pb^ls on a raneiom basis. It takes many Darken commands to turn an area completely black. These are the results ojdarkening a square one time {a),Jlve times (b), ten times (c). and twentu times (d). Trace Edges A fun command to experiment with Is TVace Edges. The premise behind this tool is that it turns the black pixels of a selected shape into white, while turning the pixels Just inside and Just outside the original pixels into black (Figure 14-7). This works on all shapes and sizes and can change the appearance of a shape substantially. On some objects, Trace Edges adds a certain body or thickness to the original shape that can be pleasing. You can also issue the Trace Edges command repeatedly in such a way that with each succeeding com- mand, HyperCard traces the edges created by the previous Trace Edges command, and so on. The effect can be quite striking when used on the right objects (Figure 14-8). Figure 1 4- 7. Trace Edges acts as if tracing the edges of shapes within a selected area. Black pixels become white and vice versa. 252 HyperCard's Authoring Environment Figure 1 4-8. You can issue several Trace Edges commands in succession, for striking ejfects. Rotate Left and Rotate Right While you might be spoiled by the intricate rotations possible during the creation of regular polygons, the Rotate Left and Rotate Right commands shift the selected images only In 90-degree jumps (Figure 14-9). Arrows and pointers of all kinds are frequent targets for the rotate commands. E^en though the commands work in 90-degree chunks, you can start with arrows that point at 45-degree angles and rotate them to 135, 215, and 305 degrees (Figure 14-10). Flip Vertical and Flip Horizontal The two Flip commands are veiy handy when you are trying to draw symmetrical shapes on a card background. The procedure is to complete one side of the symmetry— which may Include some intricate FatBlt work to achieve delicate curves or angles— and then to drag a clone of the one side. Next, select the clone and choose the appropriate Flip command. Voila: a mirror image of the original piece of art. The hardest thtng to keep straight about these two flip commEinds Is which command does which kind of flipping. Notice that flipping Is different from rotating twice. When you flip, the resulting image appears as if you are looking at it from behind the original page. Hie page has been flipped, like turning a transparent page in a book. When you flip an image vertically, the "book" containing the pages has Its spine along the top or bottom of the page; when you flip horizontally, the "book" has its spine along the side, as in a traditional book. Figure The Paint Menu 253 V 1 1 111 [ 1 1 1 !■ ) Hyp&rCardf in Figure 14-9. Rotation loorfcs in 90-degree increments. Figure 14-10. If the original image is pointed in a 45'degree direction, rotation win angle the image to 135, 215, and 305 degrees. 14-1 1 demonstrates the difference between the vertical and horizontal action of flipping a selected image. Opaque and Transparent . . ^ The two commands Opaque and TVansparent affect a selected image, Including images you paste from the Clipboard. The default setting of most Images pasted from the Clipboard is Opaque. This means that any area inside the shape's outlines is tilled with white pixels. If the selected image is dragged atop existing 254 HyperCard's Authoring Environment Flipped Horizontally 2ali1 tausl Secret Files Original 2GC«.6| UIBZ Flipped Vertically >' Figure 14-11. Unlike rotation, JUpping turns the entire image over, either horizontally or verticaUy, as you desire. graphics-layer art, the white pixels of the opaque area cover the existing art (Figure 14-12). Sometimes this does no harm and may be desired, At other times, the desired effect Is for all space inside the lines of a selected image to be clear, to let the original graphic layer show through (Figure 14-13). The best way to test which is the best effect for a particular selected image and the background graphic is to "toggle" between the Opaque and Transparent settings. These two menu items let you do just that, as long as the object is still selected. When choosing Transparent as the final mode, be especially careful to study the implications of that choice. When an image Is made transparent atop some patterns, especially regular grey fill patterns, angled lines are sometimes partially or completely disguised by the pattern (Figure 14- 14). Be on the lookout for this kind of visual interference, which may make the final background art hard to read. Keep HyperCard's automatic save feature behaves differently when the painting tools are active than when any other tool is In force. Changes you make to a background or card domain picture are not saved until V one of three things happens: 1) you exit the painting tools; 2) you go to a different card; or 3) you choose Keep from the Paint menu (or press ^ Command-K), Behind this behavior is the belief that you should be free to expert ment with the graphics layer without damaging art that has been safely The Paint Menu 255 Figure 14-1 2. Most images pasted into a graphics layer start out opaque, that is, with white pixels blocking the underlying image jrom showing through. Figure 14-13. If you want the underlying image to show through apasted image, choose the Transparent command from the Paint menu (or type the T Power Key). You can toggle between Transparent and Opaque to test which version suits the picture you are creating. 256 HyperCard's Authoring Environment Figure 14-14. Tratisparency atop JUled patterns may sometimes obscure or distort the lines of the overlaying graphic. stored on disk. You should be able to undo a number of changes in a session (with the Revert command) . Therefore, as long as you stay In the painting tools, no changes become completely final. But there will be times, In modilying a graphics layer, when youll want to save the changes made so far, and any further changes kept in memory. When you are ready to save your work to disk, choose Keep from the Paint menu. This command "keeps" the current state of the graphics on disk. Additional modifications will not be recorded to disk until the next time you give the Keep command, go to a different card, or exit the painting tools. A Keep command now and then also guards against loss of changes due to power failure or system error. Revert with changes to the graphics layer maintmned In memory until they aie specifically stored to disk, you may undo all your changes by issuing the Revert command in the Paint menu. This command reaches back to the disk and loads In the graphics layers as they weie previously ' ' ' saved to disk. The time to hit Revert Is when the changes you're making ■ " to a graphics layer are making things worse. Revert gets you back to ' where you started. ' ■ The Paint Menu 257 This ends the discussion of items In the Paint menu. As you have seen, these items perform much of the action "after the fact." that is, after a shape or text has been painted on the screen. There should be enough In the way of tools in this menu alone to let you create virtually any graphics eff^ect you have in mind. Our next stop is the Options menu, which holds some of HyperCard's real painting powers. CHAPTER 15 The Options Menu i I I In contrast to the heavily commanD'Qhiented Paint menu, the Ofhons menu contains items that you either switch on and off or that lead to dialog boxes offering a choice of settings. Every item on this menu, then, ultimately lets you set a switch that affects future graphics operations. Those items that simply turn on and off display a checkmark next to the item's name when the option is In force (Figure 15-1). If an Item brings up a dialog box with multiple choices, the menu item displays three periods after It, indicating that It leads to something else. We've already seen the effects of a couple of items In the menu, but we'll examine each one In more detail here. Grid - : Unless you've seen the effects of a grid on other painting programs, you may have the wrong expectation about what HyperCard's Grid does for your painting. In a paper environment, a grid usually helps you line up objects along vertical and horizontal axes. It helps you keep everything nicely aligned. What may disturb you about turning on the HyperCard Grid is that when you do so. nothing seems to happen, and you certainly don't see any grid lines or ruler on the screen to help you line up shapes. That's because the grid Is Invisible. How, you may wonder, can you line up objects against an invisible grid? 259 260 HyperCard's Authoring Environment Grid FatBits s/Powsr Keys Line Size... Brush Shape... Edit Pattern... Polygon Sides.. The Grid imposes a kind of linearity that doesn't work well when you < ■ ' ■ ' are doing free-form drawing with tools like the pencil and curves. And The Options Menu 261 4 File Edit Gfl Tools Paint Options i M ! 1 r i.x.±LLin. f ■i-r-i-t-i-f •• nf iitt-| : I i ~i1 ++++ ' ' I r , L I i In J f i i r i ! -t I ' 1 I \ ) [ Patteins 1 I r [■ i ' i-'-j ^ + Mi i 1 1-1 > t !■ , ■ 1 r i it t i ■ f 1 I"! '"i ! [ !~l I J, Li . + t !.i .i I j i I H ! T .f...iM.i..i.4. I- 1 1 ! I ! r h . ' i ] ■f"['":' .(...[.., M-M: .JJ..1..L ..L.U..1 "i: j "hi: 1 1 1'i' r , -| ■ Wrl: "M f j I I ^ 1 . ^ i-! I I -I i J i , ■[■■f-f ■i I '13 !-| i I !"!•}■ \\:\ I I 1 ' •! E i.| L L r I 1.J 1"i 1 H i ! ! 1 I. i J + Figure 15-2. If you muld see the Grid, this is what U would look like. When the Grid is on, cursors and drawn object 'snap to" the nearest grid intersection. Figure 15-3. The Grid helps you align objects and draw different objects with identical line lengths, such as this square and triangle. sometimes, you just need to maneuver a shape In a smaller increment that 8 pixels. Just turn off the Grid. You can always turn it on again later for other drawing. You should be aware of one aspect of Grid that may throw you at first. You'll notice it most if you create a shape with the help of Grid, turn Grid off to move the shape a few pixels, and then turn Grid back on. When you turn Grid back on, the shape does not snap back to the nearest grid line- that would be disastrous. But if you select the object with the grid on and begin to drag it around the screen. It will move only in 8-plxel 262 HyperCard's Authoring Enuironment chunks vertically and horizontally from the current position, even ry ' though it is not directly atop the invisible lines of the Grid. Therefore, ! when Grid goes on, every pixel on the screen Is frozen into the 8-pixel lockstep from its current spot. FatBits / \ i : We've already mentioned that working on graphics in normal size can i be difficult when you need to do some very fine adjustment of a few pixels. For this Job, you would turn on FatBits In the Options menu. The FatBits mode Is very recognizable on the screen because you see very large black squares representing black pixels, and a small window appears at the bottom left of the screen (Figure 1 5-4) . In FatBits you can see an area 64 by 43 pixels. It's just as if someone placed a magnifying glass over the screen. You see everything that you see in normal size, including buttons, text fields, and bit-mapped graphics. Layering is also in effect. Therefore, while in FatBits, you can turn on the It file Edit Go Tools Paint Options Patterns liliUjUIiBa ■■ ■ ■■ ■■ ■ ■■ ■■ ■ ■! mm mm m mm 1 ■ ■ ■ ■ ■ ■■■ ■■■ ■■« ■ ■■ ■ ■■ ■ ■■■ ■■ ■■ ■■■■ ■■ ■■■■■ ■■ ■ ■ ■ ■ ■■■■■ ■ I ■ ■ I mmm ■■■■ ■■■■ ■ ■■ ■ ■! 1 ■■ ■ ■■ IB ■ ■ ■■ a ■ ■■ ■■ ■■ ■■ ■■■ ■ ■ ■ ■■ ■■■ ■ ■■■ ■ ■ ■■■■ ■■ ■■■■ ■■ ■■■■ ■■ ■ ■ ■ ■■■■ ■■■ I wm MM ■ H ■ Bl ■ ■■ Bl ■ ■■ ■! ■ ■■ ■■ ■■ ■ « ■ ■■■ ■ ■ ■■■■■ ■■ ■■ ■■■ ■ ■■ ■ mm ■ ■■ ■ lo ■ !■■"■ V m ■■■ ■■ ■■■■ ■■ ■■ ■■ ■■ ■ ■■ ■ ■ ■ ■ HI HI HI HI HI ■■ ■■ ■■ ■■ ■■ ■■ ■ mm ■■■ ■ ■ ■ ■ ■ ■ ■ mm m m ■ ■ ■ ■ ■ ■ > ■ mm m m ■ ■ ■ HI ■■ ■■ I ■I ■■ ■ ■■ ■ ■■ ■ 1 ■ ■ ■ ■ ■ ■ ■■■■■■■■■1 ■ ■ ■■ m mm mmm m mm mm mmm m mmm m ■ ■■■■ ■ ■■■ ■■■■ a ■ m ■■■■ n in M 1 ■■■ n IB ■■ H ■■■■■ ■■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ 1 ■ I I I ■ ■ ■ ■■■■ Figure 15-4, FatBits magnifies graphics eight times, giving you pixel-by-pixel ':(-<'ji' manipulation powers. A small draggable window in the lower lejt comer of the }.<: . i screen shows you the actual size of the area you're workii^g on under the ; , ; microscape. The Options Menu 263 Background mode to see only what's in the card's background picture. Otherwise, you see what the browser sees: the full interaction of background and card domains. Since FatBlts is a painting tool, you'll have influence only over the bit- mapped graphics in either the background or card domains. Adjusting buttons and fields in FatBlts Is out of the question. When FatBlts Is in force, you may choose any painting tool. The cursor changes to the tool's regular- size cursor. You use the Pencil tool to point to a pixel and click the mouse button to turn black into white or white Into black. Remember, however, that because of layering effects, you won't be able to turn background pixels on and off unless you are specifically editing the background. But you can turn transparent card picture pixels to white, which gives you the false Impression that you're editing the background picture. The small window on the FatBlts screen contains a normal- size view of the detailed area covered by the screen In FatBits. That way, you can see how your FatBlts fine-tuning will impact the normal-size painting without having to turn FatBits on and off repeatedly. Notice, too, that the mini window is. Indeed, a window. You may move it around the screen by dragging its thin title bar, or you may close It (without turning off FatBlts) by clicking its close box, . ^ , 'i^i ■ \\ . SWITCHING ON FATBITS There are three ways to turn on FatBits and four ways to turn It off— that should satisfy everyone. Let's see how to turn it on first. 1. Choose FatBits from the Options menu. The first time you turn on FatBits this way after starting up the painting tools, the FatBlts window magnifies the center of the screen. If there are no black pixels or HyperCard objects In this area of your card, then the FatBlts screen and the mini window with the normal-size graphic will appear to be blank. If you want to work on an area of the card other than the center, you'll have to scroll over to it (described below). Once you've scrolled to another location, HyperCard remembers that spot and will show up there the next time you start FatBits this way. When you exit the painting tools, however, the location will be forgotten, and FatBits will come up In the center of the card the next time. 2. Double-click the Pencil Icon in the Tools palette. This action Is the equivalent of choosing FatBlts from the Options menu. They're completely interchangeable actions. 264 HyperCard's Authoring Environment Therefore, if you start FatBits once with the menu selection and scroll the FatBits view to another location on the screen, a double-click of the Pencil tool will bring you to that second location. Press Command and click on the card with the Pencil tool cursor. This is the preferred way to start FatBits if you're in a hurry. In this one action, you not only start up FatBits, but you also position the FatBits magnified view to the spot at which you're pointing the pencil tip. You bypass the need to scroll the FatBits view, This Command-key shortcut works only with the Pencil tool, but usually it is still more efficient to change tools and Command-click into FatBits. Scrolling in FatBits can be a trying experience if the destination is far from the current location (see below). SWITCHING OFF FATBITS Now on to the four ways to leave FatBits. As with all good Macintosh design, the way out is the opposite of the way In, plus one extra shortcut. 1. Choose FatBits from the Options menu. ' ' The item will be checked when you pull down the Options menu this time. Choosing this item turns off both FatBits and the checkmark next to its menu item. 2. Double-click on the Pencil tool in the Tools palette. f ' ■ This is same as choosing the item in the menu. The check mark - ' r in the menu will be turned off for you. 3. Press the Command key and click with the Pencil tool cursor. There is no positional advantage to using this method over the first two. When you leave FatBits this way, you come to the liill screen. It's here as a convenience for those who prefer this method of getting into FatBits. 4. Click any tool pointer In the mini window. This method is the simplest and requires no preplanning on your part. You don't have to worry about which tool you're using when you leave FatBits. Any tool, including the Eraser, will safely turn off FatBits without drawing or erasing on the graphic. The Options Menu 265 Scrolling In FatBits is a different experience from the kind of scrolling you may be used to In other programs. The FatBits view has no scroll bars. Therefore, you need to use a "grabber" tool, which magically appears when you hold down the Option key while in FatBits. Any tool from the Tools palette turns into the grabber, which you use with the mouse button pressed to slide the view around the screen until you see the area on which you wish to work. Because of the level of magnification that FatBits produces on the screen, it may not always be easy to find your way. Use the mini window as much as possible to help you get your bearings. If you still have trouble, then exit FatBits and re-enter it using the Command -click- and-pencU method to zoom right to the desired spot. WhUe you are In FatBits, you can use all the tools in the Tools palette, Including the selection tools and the Eraser. Moreover, the Shift key constraints and other enhancements are also in effect for those tools, even In FatBits. You'll find this feature particularly handy when you need to select a very small shape or a shape in a tightly spaced area. In Figure 15-5, for instance, we use the selection rectangle in FatBits to close up the spacing between letters In a small font. FatBits will be a frequent friend when you start designing your own graphics layers. ... a m □ o a* o A 0 TiifiX |in U p I I I.- -i" i;;p::i!::iE:ax mm m mr ' Figure 15-5. You can use all painting tools even while in FatBits. Selecting text characters, for example, gives you pinpoint precision for placing items on the screen. • •• ■• J ' ' '--i : ■ , , -r! 'ill- . III*.-. J !->,;., *; Ant. • 266 HyperCard's Auihoting Environment Power Keys V'-'A As you have probably noticed by now, HyperCard's painting tools are loaded with shortcuts, "Wfell, there are many more. Called Power Keys, they are turned on by choosing Power Keys tn the Options menu. You may also recall a Power Keys check box setting in the Home Stack's User Preferences card. When that box is checked, HyperCard automatically turns on Power Keys when you enter the painting tools (Figure 15-6). We suggest you keep that box checked if you're doing any stack authoring. With Power Keys turned on, you can issue twenty- two different commands with the press of a single keyboard key. Most of the commands you'll recognize as coming from the Paint menu, whose items we've already discussed. Others come from the Options menu, giving you the ability to turn items on and off with a single keystroke. The reason these Power Keys work is that when you're using any painting tool other than the Text tool, you really don't need keyboard keys other than Shift, Option, and Command. So HyperCard puts character keys to work for us (at our option) while painting. Obviously, when we're in the Text tool. Power Keys are temporarily disabled. In certain cases. Power Key commands require that the Message Box not be visible. When working in the painting tools, there is almost no need for the Message Box, so it's better to close it anyway. User Preferences User Name: Danny Goodman User Leuel: O Broiusing OTtJping O Painting ^ Power Keys O Ruthoring ® Scripting ^ Blind Typing < Figure 15-6. To set Power Keys as a default setting when you start up HyperCard, click the Power Keys check box on the Home Stack's Preferemxs card. - , ■>, The Options Menu 267 POWER KEYS UBRARY . ; ^ , . . - j, ,,,, . , What follows is a complete list of the keys and their corresponding commands. Wherever possible, the letter of the key is the first letter of the command. A Select All (use Command-A when Message Box is visible) B Select the Black pattern in the Patterns palette C Turn Draw Centered on/olf D Darker E ~ Trace Edges F FUl with the current pattern . - . ^ j G Turn Grid on/off H Flip Horizontally r r r ^ ^ I Invert ■':c-; -j;. • 5. if; n: L Lighter M Turn Draw Multiples on/ off 0 Opaque ' w^i'i^ P Pickup ->i •-;^'>- ■ -n- O.-: -^^ 'i R Invert 5 Select (Command-S selects the current text when the text tool is active; also use Command-S when ^ - Message Box is visible). T TVansparent iT» wrV^; lir V Flip Vertically W Select the White pattern from the Patterns palette 1 Set line thickness to 1 pixel 2 Set line thickness to 2 pixels . 3 Set line thickness to 3 pixels ' ' ' ' ' 4 Set line thickness to 4 pixels . . 6 Set Une thickness to 6 pixels 8 Set line thickness to 8 pixels , ■.< / , ; . : [ Rotate Left , . 1 Rotate Right Backspace Clear the current selection 268 HyperCard's Authoring Environment Power Key commands that control Paint menu choices require that a shape or screen region be selected first. If you forget to select a shape. / an alert box will tell you so. After the alert box, you'll still be able to select with the S Power Key the last shape you painted. For some Power Key commands, repeated pressing of their Power Kty ■ " ' Is the same as toggling back and forth between two views, as In the Flip commands. Other commands, like Lighten and Darken, are veiy practical as Power Keys because they require many activations to make a significant visual difference. Pressing the D key ten times is much more convenient than choosing Darken from the Paint menu ten times. Line Size We've seen the dialog box that this menu selection gives us (Figure 15- 7). Whatever line thickness you choose in this graphical dialog box applies to the lines drawn by all tools except the Pencil. Brush Shape Here is another way to get to the brush-shape dialog box for selecting one of the thirty- two possible shapes (Figure 15-8). Your selection here affects only the Paint Brush tool. Edit Pattern.,, Previously we've hinted at the possibility of editing the pattems in the , .J ,^ Pattems palette. Well, it's true, and the Edit Pattern... command In the Options menu is one place of entry to do just that. When you choose this item, HjrperCard presents a small dialog box with a FatBit-style editing window (Figure 15^). In this box are both a magnified version of the pattern and a square area in normal size to show you what the pattern looks like in its typically repeated setting. It's time we took a minute to explain pattems in more detail. INSIDE PATTERNS A Macintosh pattem is determined by the black and white pixels in an 8x8 square. At first glance, that may seem hard to believe, considering some of the intricate pattems you see in the Pattems palette. But all of those pattems consist of a repeated 8x8 pixel pattem. Examine them The Options Menu 269 Figure 15-7. Une Size dialog box ■ • / \ ■ • \ ■ • □ Figure 15-8. Brush shape dialog box Figure 15-9. Edit Pattern dialog box. You can edit patterns here in FatBtt style, with a representatkie sampling of the resulting pattern in the right-handwindow. HyperCard's Authoring Environment yourself. Select a pattern In the palette and then choose Edit Pattern from the Options menu (you can also double-click on the pattern in the palette to bypass the menu). The patterns in the palette were carefully designed so that the top edge of one 8x8 square blends into the bottom of the 8x8 square that would appear above it on the screen. You may use FatBit techniques to edit a pattern pixel-by- pixel. As you do, the change in the pattern is immediately reflected in the sample on the right. The number of combinations is large enough to keep you busy for weeks. An important point to remember about patterns is that as you draw aJiUed object and uJhen you Jill an outline with the Paint Bucket toot, the pattern is fixed within the coordinate system of the Macintosh screen. That's a mouthful, so we'll demonstrate what we mean with two examples. In the first example, we'll draw a filled pentagon, using one of the hrlcklike patterns In the Patterns palette. Try this yourself to get the full effect of this demonstration. As you drag and rotate the pentagon during its creation, the pattern does not rotate with the border shape. In a sense, the pattern remains fixed in the coordinate plane of the screen, no matter where you start drawing the object or how you rotate it during the creation process. As a second demonstration, let's draw a filled square with a pattemed border (that's done by holding the Option key down, remember?) with a tricky border, like the three-dimensional square pattern (Figure 15- 10), Before we proceed, be sure the Grid is turned off, to prove that you're not under its influence. Now, with the same pattern, select the Oval tool and draw a filled oval with a pattern border (Option key enhanced) on top of the square (Figure 15-11). Notice that the patterns merge perfectly. Undo the oval and try again in a different spot. The r* (□□nnnnnnnncn * inDcnciDnnnnDn incccririnDDticiE] lODEicicinnnnDnii U iDcnnDnnonncn ^ [□□□nnnnnccDD } iEC3nnnnnnccinn -:, innnnnnncDcnn v Figure 15-10. To demonstrate the inner workiT\gs of patterns on the painting screen, begin by drawing a JUled, patterned border square with a compkK pattern. The Options Menu 271 (□□□□DDDGnnnn .^□□□□□□□DcicQnnnnDDcnnFj 'nDDDcnciDcciciciDDnDDEicinnr -"nnnnnnnnnnnoonnccr'- innnDDCcnnnnn* — innnnnnnonpgn Figure 15-11. Then draw another^fUled shape, also with a patterned border. The location oj the pattern remains constant with respect to the screen. The minute you select and drag the shape, however, the pattern may lose its registration. results will be the same, because the pattern drawn for the square and oval is "nailed down" to the same coordinate plane. PATTERNS AND BIT MAPS The situation gets a bit more complicated, however, when you select a filled area and move it around the screen. Recall that we said text characters become mere black pixels on the screen once we click the text pointer elsewhere. The same principle applies to patterns. As soon as we release the mouse button when drawing a shape, the pattern becomes a bit map, no longer tied to the original coordinate plane of the starting pattern. Therefore, you could shift a fllled shape on the screen a couple pixels and be out of registration with the same pattern when It Is used to draw or fill a new shape. You will probably encounter this registration problem first when tiying to match a grey fill pattern cut and pasted from another picture. Because of the tightly knit, repetitive nature of the pixel pattern that makes the grey pattern, you have a 50% chance of placing the pasted grey pattern in precisely the same orientation as the existing material (Figure 15-12), With the marquee swirling around the pasted selection. It's often difficult to see where it's "safe" to accept the paste procedure. For patterns with a less tightly knit pixel arrangement or a less- regular pattern, the chances can be much less than 50%. It may take several attempts at pasting and careful positioning before you get it just right. If you move a fllled shape In such a way that it comes off the registration of the live pattern, you still have a way to use the Paint Bucket tool to fill with the same off-registration pattern. It entails editing a pattern to match the new one— something you can do with a single click of the mouse. In a tjrpical setting, you may copy a piece of a card background or other Macintosh program screen to use as a foundation for a stack 2 72 HyperCard 's Authoring Environment b<^^ ■_■ ■ ■ ■ ■ ■ Figure 15-12. Two squares of the same grey fill pattern wer^ pasted atop (he original. The top square happened to maintain full registration with the original; the bottom was off by one pixel This tight pattern gives you a 50-50 chance of perfect registration thejirsl time. you're building. Let's say that piece has a grey fill pattern around it, and some of that pattern is inclu ded in the section you paste into your new background (Figure 15-13). When you're finished adding your own touch to the graphic, you then want to fill the rest of the screen with the grey pattern. Applying the Paint Bucket, however, reveals that the grey you pasted is sHghtly off registration from the live pattern that HyperCard uses for drawing and filling (Figure 15-14). What you need to do is edit a pattern to coincide with the pattern as you pasted It. Full down the Patterns menu and select a pattern you won't be using during this HyperCard session. Then choose Edit Pattern... from the Options menu. The dialog box with the FatBitted pattern will appear. Now, simply click on any spot of the background grey pattern that you're trying to match. HyperCard will read that pattern and devise a live pattern that matches it. For the moment, this new pattern has taken the place of the unused one in the Patterns palette (this won't survive the exit from the painting tools). You can now The Options Menu 273 Birthdays & Anniversaries Figure 15-14. When inter filled around the pasted shape, the pattern is Indeed off registration by one pixel You can edit a pattern to match the off-registration one. 274 HyperCard's Authoring Environment fill the rest of the screen with the Paint Bucket and your new, temporary pattern (Figure 15-15). This has been a crash course in Macintosh patterns, but all the details are here for you to study and experiment with at your leisure. As with fonts, keep the number of patterns on a screen to a visually appealing few. As professional artists will tell you, sometimes empty white space around elements makes a stronger statement than pat- terns. Polygon Sides The dialog box summoned by this menu item shows the six types of polygons you can choose (Figure 15-16). A more efficient way of reaching this box, as noted earlier, is to double-click on the Regular Polygon tool in the Tools palette. Draw Filled ''I The Draw Filled Item is an on/ off switch, which is uniformly accessible by double-clicking on all shape-drawing icons except the regular polygon. As extra feedback to show you that Draw Filled is turned on, the tool Icons in the palette show a grey fill pattern. Note that this pattern is not necessarily the pattern selected in the Patterns palette; it fills the tools merely to indicate that Draw Filled is turned on. Draw Centered WeVe seen the effect that turning on Draw Centered has for most of the regular shapes. Only the regular polygon automatically draws from the center. All others— lines, rectangles, and ovals— must have this svritch turned on to function. Follow directions provided earlier in our discussions about rectangles and ovals to draw concentric shapes. The centerpoint technique is one you should master. The Options Menu 275 Notes Birthdays & 1 1 Anniversaries 1 Figure 15-15. After editing a pattern to matcK the new JUl pattern blends seamlessly with the pasted pattern. Figure 15-16. Regular Polygon dialog box .ft DrawMultpJe In our discussion about regular polygons, we indicated the kind of effects you can attain when the Draw Multiple feature is in force. It also works when drawing other shapes, including rectangles and circles. 276 HyperCard's Authorir^ Environment Once you turn on Draw Multiple, you can set the Interval between repeated images by pressing the Option key and any number from I through 9. Figure 15-17 demonstrates some repeated drawings. In the next chapter, we'll close our painting discussions with com- ments about painting In general. F^ure 15-1 7. Examples of what you can do with the Draw Multiple feature engaged CHAPTER 16 Painting Strategies NoraiNG CAN BE MORE FRIGHTENING THAN A BLANK PAGE, ESPECIALLY IF YOU'RE expected to work in a medium— graphics— that is foreign to you. Using the painting tools buUt into HyperCaM should ease the pain considera- bly, but you may not know where to begin. Borrowing from Others Perhaps the easiest way to begin designing a stack background graphic is to borrow ideas from existing Macintosh programs whose looks appeal to you. The Macintosh actually provides you with the tools to copy and paste part of a Macintosh screen into a new background you're creating. Here are the steps: 1 . With the screen you wish to adapt showing on the screen, press Command-Shlft-3. This three-key combination saves the entire screen, including menubar, as a MacPaint document file on the disk with the name Screen 0. Each time you press this key sequence, a new file is created, with the number In the file name increasing automatically by 1 until it reaches 9. After that, the Macintosh won't let you do any more "screen dumps" until you change the names of the existing Screen files. 277 2 78 HyperCard 's Authorir^ Environment ^ : - . Enter HyperCard and bring up the blank background you wish to start work on. - ~3. - ■ Select any painting tool from the Tools palette. ,««a. Figure 17-22, 300 HyperCard's Authoring Environment 4. Click and drag the selection to the left about one-half inch . (Figure 17-23). o: b-y-jj ■■ii> As an exercise, you should also drag the selected image to the . v! / /; , i, • right for a moment to uncover what's really going on. Under the >d / Ki) : : , selection rectangle, the original image of the card's left edge is j. i . . - . intact. You're actually dragging a copy on top of the original. By ) M ' dragging it only a small way to the left, the copy covers up the ?ft- i original left edge, but also leaves some of the original top and bottom edge lines. The net effect when you're dragging to the left " ^ is that the top and bottom edges are leaving "tire tracks," when ■ ' ^ In reality you're seeing the original lines. ^ File Edit Go Tools Pai o i «p , 'a U L »t. o c A O c 1 F^ure 1 7-23. Building a HyperCard Stack 301 When you're satisfied with the position of the new left edge, click the mouse pointer outside the selection rectangle to turn off the marquee. When you release the marquee, the new bit map completely covers up the original left edge (although you can undo the action Immediately if you need to). Repeat steps 1 through 5 with the right edge of the card, but don't Include the card heading text In the selection rectangle. Use the distance between the card edges and the screen edges as a visual guide to make the left and right sides of the card as equidistant from the screen edges as possible (Figure 17-24). Because the art for the calendar button is an icon, rather than background art, the selection tool won't affect it. ADD A DROP SHADOW Most viewers of Macintosh applications sense a certain depth or three- dimensionality to many of the Images that appear on the screen. Even the pull-down menus have an overlapping feeling when they appear on the screen. *F»eEdlt 6o Tools Paint Options"Patterns 7:43 "^^^^^ i^^3^ ^^'d^^^H^si^l^ O A '-^ n O d> o A O r? Figure 1 7-24. Exttnd 302 HyperCard's Authoring Environment , Most of the time, this effect is caused by what is called a drop shadow. , , Pull down a menu and examine the right and bottom edges closely (Figure 17-25). Notice that these two sides are thicker than the one exposed on the left. Not only that, but look very closely at the missing pixels at the top of the right line and at the left of the bottom line. The net effect is that the eye is tricked into thinking there is a Ught source up and to the left of the screen that is casting a shadow behind the i K ; menu. ' You'U see this drop shadow effect on many Macintosh devices, including windows. All standard Macintosh windows have a drop ; , . shadow. This was designed into the toolbox that programmers use to . ' generate screen windows. The purpose of drop shadow windows is " \, particularly evident when you have multiple windows open at one time. Drop shadows give each window a feeling of depth and tangibility. We forget that the screen is a combination of dots; instead, we see thr^e dimensional "layers," Drop shadows don't have to be limited to single-pixel thicknesses, Sometimes a more dramatic drop shadow effect can be achieved by a >.',' very wide shadow, as shown in Figure 17-26. The thickness of the : . shadow and Its distance from the top right and bottom left edges affect ^B two visual factors: 1) the angle of the light source; and 2) the distance of the primary object from the perceived backdrop. Not every card, window, or other screen object needs a drop shadow to be effective. In fact, even our To Do card could survive nicely without ;■ \ a drop shadow around it. We're showing you how to do it primarily as an exercise, so that you can repeat the technique m other stacks where it may be more appropriate. Also, don't get carried away with drop I shadows. Use them In moderation. And exercise care In using thicker \ drop shadows. You may find yourself making a mess of a simple graphic, particularly if you try to mix drop shadows of varying thickness on the same card. With that understanding, let's add a two-pixel- thick drop shadow to I the To Do card. I 1. Double-click on the Straight Line tool to bring up the line- thickness dialog box (Figure 17-27). 2. Click on the second line from the left (Figure 17-28). ' 3. Select the Straight Une tool from the Tools palette. ... . - The cursor changes into the cross-hair pointer. This cursor has an Important propeity that you'll use to help you position It accurately In the next step . Whenever a black pixel of the cross J - hair Is atop another black pixel, the cross-hair pixel turns * ' " white. Therefore, when it is atop a vertical line, the vertical ofthe BuOdtng a HyperCard Stack 303 ■■■ ■■! ■■ ■■ ■ 1^ Figure 1 7-25. Single Shadow Double Shadoui Is IIEIllIlilil iS ■ H 5-line Shadow Figure 1 7-26. Figure 1 7-27. 304 HyperCard's Authoring Environment 1 ■-1 1 1 1 1 1 Figure 1 7-28. ; j cross hair turns white. You can use this property to make sure [ the cross hair Is on or off existing lines. . ' 4. Using Figure 17-29 as a guide, position the cross-hair cursor i tmmedlately next to the right edge of the card and a couple of ' pixels below the top edge. | The exact number of pixels below the top edge is not Important s now— we'll make final adjustments in a moment, with the help \ of FatBits. What you need to watch, however, is that the cross- \ hair cursor be Immediately adjacent to the card's edge. Gently j I jtterns ' . . . . . Y- Y^ BuMing a HyperCard Stack 305 move the cursor to the left and right. Notice how one vertical strip of the cross hair's pixels turn white when it is atop the card's edge (Figure 17-30). For the drop shadow, you want the cross hair to abut the card edge, but not be on top of It (Figure 17-29). ? 5. Hold down the Shift key and drag the cursor down to Just below the bottom edge of the card (Figure 17-31). TTie exact measure below the card Is not Important now. 6. Repeat steps 3 through 5, but starting at the left end of the bottom edge of the card (Figure 17-32). When you Shift-drag the line to the bottom right comer of the card, you can extend the line beyond the edge for now. 7. Select the Pencil tool from the Tools palette. The cursor changes into a pencil cursor. 8. Place the pencU cursor near the spot where you began drawing the vertical line (Figure 17-33). :==□ Figure 1 7-30. 306 HyperCard's Authoring Environment -1- Figure 17-31. To BMk3Mk Tdtieiii' o ilEEEEHiE s i. □ o <^ o CO A O Figure 1 7-32. Building a HyperCard Stack 307 Figure 1 7-33. 9. Hold down the Command key^ and click the mouse button. This brings you into FatBits, looking at the place where the drop shadow begins, 10. Where necessary, add or remove black pixels In such a way that the start of the heavy drop shadow line Is on line with the third pixel down the card's left edge, as shown tn Figure 17-34. Notice the instant change to the normal- size drawing In the mini window as you change each pixel. 11. Hold down the Option key (the pencil turns into the grabber cursor), and with the mouse button also held down, scroll to the lower left comer of the card inside FatBits. It will take several drags across the screen to reach the opposite comer. This exercise should give you the feel for scrolling within FatBits. You could have also exited FatBits and re-entered, repeating steps 8 and 9 at the opposite comer. 308 HyperCard's Auttwring Environment Figure 17-34. , , ^ . , , , 12. Where necessary, add or remove black pixels from the drop shadow line, so that it starts at the third pixel of the card's bottom edge, as shown In Figure 17-35. 13. Exit FatBits (there are four ways to do this, remember) and re- enter FatBits by placing the pencil cursor at the bottom right comer of the card, holding down the Command key and clicking the mouse button. 14. Add or erase black pixels on the drop shadow line until the comer looks like the one in Figure 17-36. 15. Exit FatBits once more. -^-- v ? "- - ; That's all there is to making a drop shadow. It may seem like lot of steps here, but it all goes rather quickly after you've do a few. Burning a HyperCard Stack 309 1;:;- 1 1 1 1 1- ^ ^ LJ CD O A o .r. i ■■■■■■■ Figure 1 7-35. i File Edit Go Tools Paint Options Patterns □ h o 1 1 r — n 1 1 1 1 a o c? A O a. B! ■■ u ■■■■I *''-I>-!ly>- ■ .TV *. Figure 1 7-36. 310 HyperCard 's Authoring Environment REMOVE BACKGROUND TEXT In this task, you'll be removing the word "today" and any other extraneous text from the background graphic. Later on, you'll add some card-domain graphics to take its place. You could use the Eraser to remove the word, but let's try a different approach, one that you will find useful In other situations. Before you begin, make sure you are still in the background editing mode. 1. Click the Selection tool from the Tools palette. 2. Drag a selection rectangle around the word "today" and other text In the background graphic (Figure 17-37). 3. Press the Backspace key. In a flash, the text is gone. You could have chosen Cut from the Edit menu, and saved the word In the Clipboard. But since you won't be needing it again, it's best to just do away with it in a single keystroke. You can stUl undo this kind of erasure, however. ^Jih. ^^Ph. 1*11^1^ TPjih jpfciM ii Ml ■ _ ::| |::: h HP 1 1 o O CP A O Figure 1 7-37. BuMtng a HyperCard Stack 311 ADD DAILY BUTTON GRAPHICS A major addition to the functionality of this To Do stack rendition is a series of buttons across the top of the card that will let you zip immediately to the To Do card of any day of the week. In other words, you won't have to flip card after card to advance several days. You'll Just click on a button for the desired day. The buttons will be fairly small and labeled with the first letter of each day of the week: S M T W T F S. You'll put the graphic design for the buttons in the background graphic layer, while the button link actions wUl be included In transparent background buttons that you'll add later. Howyou design a button graphic Is a personal choice . In this exercise, the design is a simple square with the day's letter Inside it. The letters will be in the Chicago font, which has a nice bold feel to it and is one of the most readable fonts in the standard font library. Later in this chapter, we'll show you how to add a highlighting feature to the buttons so that when you are viewing Wednesday's card, the W button will have a heavy border around It, Since most of the drawing of these buttons will be on a relatively small scale, a lot of the work will be done in FatBits. Among other things, you'll see how to work with several tools while in FatBits. Again, be sure you are editing the background for this task. v s : iv- 1. Select the Pencil tool from the Tools palette. 2. Position it approximately in the center of the card, near the top edge (Figure 17-38). o r 1 r — T 1 1 h □ o o A O Figure 17-38. = .r? .^v;^; vA-j-jii > ;,,■,;:... • Xj oi ' "/s 312 HyperCard s Authoring Environmsnt We'll start working up here. If we find we need to move the results, we can do so later for all the buttons we draw. Hold down the Command key and click the mouse button to enter Fat Bits at this location. Double-click the Straight Line tool and select the single-pixel thickness line. Select the Rectangle tool from the Tools palette. The cursor changes to a cross hair. Place the cross-hair pointer near the upper left comer of the screen and drag a rectangle, as shown in Figure 17-39. For the best results, draw the rectangle with the same number of pixels on each side, as shown in the Figure— 16 pixels across and 16 pixels down, including the one already in place from drawing the horizontal line. Select the Selection tool from the Tools palette. Hold down the Command key and drag a selection rectangle around the rectangle you just drew. The selection rectangle snaps to the rectangle you drew, so when we clone the rectangle in the next step, we won't get any superfluous white pixels with it. . , When you're in FatBits, the selection rectangle is also In FatBits, so it may seem odd at first to be working at such a large scale. But it turns out that you have far more control over the selection rectangle (or any tool, for that matter) when working within FatBits. I 9. Hold down the Option and Shift keys, and drag a clone of the ... rectangle to the right, so that you have a second rectangle spaced one blank pixel from the first one (Figure 17-40). The Shift key keeps the clone constrained to the horizontal plane of the first rectangle, eliminating one alignment concern. You now have two options for continuing the cloning proce ss . You can do it in FatBits, in which case you'll have to scroll the images to the left to make room for the third clone (keep dragging the selected rectangle by holding down the Option and Shift keys) . You may also exit FatBits ' and try your hand at some precision work In normal size. Use the same , selection and clone procedures in normal size (Option and Shift before " dragging) . and use the distance between the first and second rectangles as a guide to the spacing between the remaining rectangles. 3. 4. 5. 6. • • imji 1' 7. . 8. BuMtng a HyperCard Stack 313 4 File Edit do Tools Paint Options Patterns □ Figure 1 7-39. 1 n'>;,y io> . .j.-. 'iicoi. at '.--r-j' Aaiio- v' ''• >c h o 1 1 nlo <5» o A O Figure 17-40. 314 HyperCard's Authoring Environment 1 0 . Repeat the cloning process until you have a total of seven evenly spaced rectangles, all on the same horizontal axis (Figure 17- 41). If you cloned in normal size, you may always return to FatBits to check the rectangle spacing. Adjust the spacing In FatBits by selecting a rectangle and dragging it In the desired directlon- wtthout the Option key, however, because you are moving, not cloning. ^ Now you'll add the letters for each button, 1 1 . Double-click the Text tool in the Tools palette to bring up the Font dialog box. 12. Select the Chicago font in 12-point size. Leave other settings as they are, and click OK. 13. If you are in FatBits, exit it now. Click the text cursor directly above the leftmost rectangle (Figure 17-42). 14. Type a capital letter S for Sunday (Figure 17-43). 15. Press the Spacebar twice, so that the flashing text point is approximately centered over the second rectangle and type M for Monday (Figure 1 7-44) . 16. Continue this process for each day of the week, typing the letters T, W, T (some people prefer R for Thursday to differen- tiate it from Tuesday), F, and S above the centers of their respective boxes (Figure 17-45). . -f^ 17. Use the Command key and Pencil tool to enter FatBits so that you are viewing the leftmost rectangle and the letter above it. If you place the Pencil tool between the letter and the rectangle, you should bring both into view Immediately upon entering FatBits. 1 8. Select the Selection tool from the Tools palette. 19. Hold down the Command key and drag a selection rectangle around the letter S above the rectangle. The Command key teUs the selection rectangle to snap to the rectanguleu" area specified by the outermost pixels of the letter, 20. Position the cursor over any pixels of the S so that the cursor turns into the arrow. 21. Drag the letter into the center of the rectangle (Figure 17-46). Notice that the rectangle was sized to allow the letter to be centered vertically with two blank pixels above and below the BuOding a HyperCard Stack 315 To Dd lillMiBIMSBH. ^ Figure 17-41. □□□□□□□ ■ F^ure 17-42. □□□□□□□ F^we 1 7-43. s m| □□□□□□□ / Figure 17-44. ;. ; " ■ ; ,v/ , . s MT 111 H F s| 'Vj/ i. > □□□□□□□ ; i Figure 17-45. 316 HyperCard 's Authoring Environment * File Edit Go Tools Point Options Patterns mm mm IHi -SB M T li Figure 1 7-46. o n mm- □ o o c A 0 a 22. 23. letter. Also be sure the letter Is centered between the left and right sides of the rectangle. Repeat steps 18, 19, and 20 for each of the letters. You may remain in FatBits to finish the Job. Remember to hold down the Option key to turn the Selection tool cursor temporar- ily into the grabber for scrolling around inside FatBits. When you are finished placing the letters, exit FatBits (Figure 17-47). You are now finished with the background graphics modifications, But you still have two major background tasks to complete. The first is to work on the background fields. Modijy Background Fields This stack came with two text fields as standard equipment. One field, the smaller of the two, won't be used for this stack. Delete it now. 1. Select the Field tool in the Tools palette. : Outlines surround both background fields. nuu Building a HyperCard Stack 317 To INl [I][M][I][l[I][F][ll ^ Figure 1 7-47. 2. Click on the small field just below the calendar button. The field outline turns into a marquee. 3. Press the Backspace key. ' !' The field disappears. Now you can focus on the large text field. Because of the graphic changes made to the size of the card, the available text area is too wide to make a single field practical. Considering that most items on a To Do list will be less than ten words, the space on the right side of the card would be wasted. Why not turn that space into a second colunm? Then you can divide your To Do tasks into two categories, such as items that must be accomplished on a certain day, and long-term items that need gradual or protracted attention. Shrinking the depth of the CEird reduced the number of lines you can have in the column. But since the font of the field as copied from the Stack Ideas stack is in a 14- point New York, we can choose a different font and font size to squeeze more lines into less space. With our overall target in mind, let's begin this task. 1. Select the Field tool at the top of the Tools palette. The border around the single lairge field will become visible (Figure 17^8). . . . . 2. Double-click on the field to summon the Field Info dialog box (Figure 17^9). A quick glance at the field's attributes reveals that it wiU show its own lines and is transparent. That's fine for our purposes. 318 HyperCard 's Authoring Env ironment ToCN» P h □ o o z> A o a Figrure i 7-48. Field Name: Bkgnd field number: 1 Bkgnd field ID: 4 □ LoclcTeHt * V lEt Shoup Lines □ LUide Margins C Font... 1 [ Script...^ I OK I [ Cancel ] Style: (§) transparent O opaque O rectangle O shadoiu O scrolling Figure 1 7-49. 3. Click on the Font. . . button to change the font attributes of this •w-S field, . r>,tj.*i.- 'M-.i-^-^tT, T: ■ -if'^ 4. Select Geneva in 12 point, and click OK (Figure 17-50). ; You return to the card view, with the field selected. 5. Grab the field near its center and position the top left comer, as shown in Figure 17-51. i»vv ■ ; ; - ' ■ : . ■■ ^ ■ □ □ o ! ■ ■ « J A 0 FigLire i 7-52. Td HCI IlfMlfTfiiilfRlfFin my o r — ^ 1 1 b- J □ o o A 0 a Figure 1 7-53. ' : ' Since you have set the font and other attributes In the first field, the clone will have identical settings. • ' 8. Select the Browse tool to see how the text lines wUl look in every card. ..»rjl=. t;^jv*- ■ ■ That completes the field modification for this stack. Simple enough, wasn't It? Now to the buttons. Building a HyperCard Stack 321 Delete Background Buttons Five of the six buttons provided with this stack— all but the calendar button- won't be needed. You'll delete these buttons now. 1 , Select the Button tool. AU but the Extend button show their outlines. The outline of the shadow style Extend button blends with Its own border, so you can't see It. 2, Click once on the Home button at the lower left to select it. 3, Rress the Backspace key. . ••, - ■ 4, Repeat steps 2 and 3 on the four other buttons at the bottom of the screen, Including the Extend button, ^ . . You're now ready to add some new buttons. Add Background Buttons ' ' • ^ - - ' The remaining button links the stack to the Calendar stack supplied with HyperCard. You're about to give your new stack substantially more linking power to other cards in this stack and to other stacks. Hie first task vrfll be to add an icon button linked to the Name and Address stack. Then you'll create the buttons that go atop the seven- day button art you Just created. Finally, you'll create one more icon button that you'll be able to copy and paste in other stacks (including the Home stack and weekly appointment calendar) to gain immediate access to your To Do list at the click of a button. MODIFYING AN EXISTING BUTTON The existing button with which you'll start is in the background. While you could make some adjustments to this button whether or not you are officleilly in the Background editing mode, you wHl be cloning the button and creating some new ones in the background. Therefore, make sure you are in the Background editing mode before you begin. 1. Select the Button tool from the Tools palette. A rectangle around the Calendar button Indicates that you are in the button editing facility at the moment. 2, Click once on the Calendar button to select it and drag it closer to the upper right comer of the card. 322 HyperCard's Authoring Environment 3. Hold down the Option key and drag a clone of the Calendar button to the left (Figure 17-54). Behaving dutifully as a clone, the second button retains the icon, name, and script of its forebear. You need to change a few things about it. 4. Double click the clone button to bring up its Button Ir:fo dialog box. 5 . Type a new name, such as 'To Name/Address, " for the button. 6. Click the Icon. . . button and select the icon representing a rolo- flle address card (the one we use has the id number 3430). All other attributes of the button are fine, except for the script, which we'll handle right now. 7 . Double-click the new button to see its info dialog box. and click the Link To., , button. The Link window appears, instructing you to go to the card this button should Itnk to. 8. The Browse tool is automatically selected, so navigate your way back Home and into the Name and Address stack. ■ 1 -J • 4n- ■ r ~ T 1 1 1 1 1 1 O o A O Figure 1 7-54. BuUding a HyperCard Stack 323 9. When the first card of the Name and Address stack is on the screen, click the This Stack button in the Link Window. The link is automatically established in the button's script, and you are brought back to the To Do card. You can try your button now. If you like. Click on it with the Browse tool (Figure 17-55). If you followed the steps above correctly, you will go immediately to the Name and Address stack with the zoom open visual effect. If you get different results, repeat steps 7 through 9, above. Your next task is to copy abutton from one of HyperCard's button idea stacks and paste it Into your new stack. 10. Type Command-M to show the Message Box. 1 1 . Type Go "Button Ideas " into the Message Box and press Return. 12. Use the stack's Index to find a button for Telephones or type Go card ID 6144 into the Message Box to go directly to the card. 13. Select the Button tool from the Tools palette, and click once on the telephone button, shown in Figure 17-56. This button contains a script that dials a telephone number. s1[Ml[T][Iiil[R][r|[s mm '. 1 r- -* T 1 1 1 1 O O A O Figure 1 7-55. HyperCard's Authoring Environment * File Edit 60 Tools ObjB cts Home, Business [lndeH)[M|| lift iPHMHifflitl r — -1 1 1 'Ik □ 0 0 A 0 a Figure 1 7-56. 15. 16. 14. Choose Copy Button from the Edit menu, or use the keyboard shortcut, Command-C. This puts a copy of the button (attributes and script) into the Clipboard. Now type Go "My To Do List' into the Message Box and press Return to return to your new stack. Choose Background from the Edit menu, and choose Paste Button from the same menu (or type Command-V to paste). A copy of the dial button will appear on the card in the same place as It appeared in the Button Ideas stack. The button Is still selected. Drag the selected dial button to a spot to the left of the Name and Address icon button {Figure 17-57). i If you need the space, move the icon buttons around a bit to accommodate all three buttons. That completes the modification and copying of existing icon buttons for your new stack. The next task is to make new buttons for the days of the week. 17. Building a HypeTCard Stack 325 S][M]|T|[m][R][?][| B r ^ T 1 1 1 1 o O A O JTgure 17-57. CREATING NEW BUTTONS You'll need seven buttons. Recall that the best strategy for this installation Is to create the iirst button and set as many attributes as possible. Then clone that button for the others. 1. Make sure you are In the background editing mode before proceeding. 2. Choose New Button from the Objects menu. A named, round rectangle button appears selected in the center of the screen. A number of attributes need changing before you begin cloning. 3. Double-click the new button. ' This brings up the Button Info dialog box for the new button. 4. Change the name of the button to Sunday. 5. Uncheck the box next to Show Name. , ; ; > . 6. Click the radio button for the Transparent button style (Figure 17-58). 326 HyperCard's Authoring Environrmnt Button Name: Sundayj Card button number: 1 Card button ID: 2 □ Shouj name □ Ruto hilite [ Icon... LinkTo... ] Style: <9ltransparent 0% pa que O rectangle O shadow O round rect O check boK O radio button [ Script... ] I OK I Cancel Figure 1 7-58. 7. 8. 10. 11. 12. Click OK in the dialog box. ' The new button has lost its visual attributes but Is still selected on the screen. Drag the button to the row of day button graphics in such a way that the upper left comer is directly overlaying the upper left comer of the Sunday button graphic (Figure 17-59). Grab the bottom right comer of the selected button and shrink the button so that the swirling marquee completely covers the outline of the Sunday button (Figure 17-60). Hold down the Shift and Option keys, and "peel ofT a clone of the Sunday button to the right. Place it carefully atop the Monday button (Figure 17-61). Continue cloning with the Shift and Option keys until all seven buttons are created (Figure 17-62). Select each of the buttons hi turn and assign the name of their respective day to the name of the button, as you did for Sunday in step 4, above. Building a HyperCcmi Stack 327 aSlilliijILBJiFjH ■ ■■■3 ■■■JBII r — T 1 1 1 1 o o c? A O retire J 7-59. |:-::| 1 T 1 1 1 1 O o C9 A O Figure 17-60. 328 HyperCctrd's Authoring Environment Figure 17-61. Figure 1 7-62. These buttons are not yet linked to any card. We'll get to that in the next task. Making the Cards In the card domain for this stack, the only layer you'll be dealing with is the graphics layer. All buttons and fields are in the background. But the graphics layer of each caid will Interact with the background graphics layer. ADDING NEW CARDS ; > ■ Since the stack currently contains only the one card that is automati- cally generated when a new stack is created, you'll have to add six new cards to the stack. 1. If you are In the background editing mode, exit it by selecting the Browse tool in the Tools palette. 2. Choose New Card from the Edit menu a total of six times. The keyboard command shortcut— Command-N— comes in handy for this operation. Pressing Command-N six times In a row is a lot faster than making the menu choice six times, 3. Type Go to first card into the Message Box or choose First finom the Go menu. This assures that you start assigning days to the cards irom the very front of the stack. Building a HyperCard Stack 329 At this point, you should decide which card you want to be the first one in the stack. It won't matter while you use the stack, but the first card is the one that HyperCard displays when you open the stack from the File menu or from the To Do icon that maybe on another stack Even though weVe set up the dally buttons to start with Sunday, that is no reason to make Sunday the first card. Since Monday is usually the shocker of the week, perhaps that's the one to make the first card. 4. Select the Text painting tool from the Tools palette (Figure 1 7- 63). 5. Double-click on the tool to bring up the fonts dialog box. 6. Select Geneva 18. You're about to add some card layer text to run on with the background text. 7. Click the Text pointer about one and a half inches to the left of "S" button, and type Monday (Figure 17-64). Don't worry if the word doesn't line up with the buttons. TTiat's what the next steps are for. 8. With the Command key down, drag a selection rectangle around the word Monday. 9. Carefully adjust the location of the "Monday" so that It is on the same base line as the day buttons and has enough room to the right to accommodate the longest day name, Wednesday (Fig- ure 17—65). 1 1 1 — 1 p 1 1 O O mo a Figure 17-63. 330 HyperCard's Authoring Environment Figure 17-64. -„ [ , Figure 17-65. 10. Advance to the next card and repeat steps 7 through 9 for Tuesday, Repeat this procedure for each card through Sunday. The text font and size you selected for the entry of "Monday" Is still in force, so you don't have to get to the fonts dialog box prior to typing each card's day name. From here you go to another graphics task: placing the highlight rectangles on each day's card. Building a HyperCard stack 331 ADDING A CARD LAYER GRAPHIC With a septate card for each of the seven days In the rolling To Do stack you have the luxury of adding custom graphics to each day's card. In this exercise, you'll be adding a highlight- a heavy border- around the dally button of the day whose card you're viewing. Thus the Monday card will have a heavy black rectangle around the M button. Be sure you are not in the background editing mode, because these graphics go into the card graphics layer. Starting with the Monday card, enter FatBits and bring the M button into view near the center of the screen (Figure 17-66). Double-click on the Straight Line tool to summon the line thickness dialog box. Choose the third line from the left (Figure 17-67). 1. 2. 3. 4. * FHb Edit Go Tools pnint Options Patterns la Figure 1 7-66. ■■■ ■■■ ■■■■ !■■■ 3 ' ss O m P i n o o A i! 3 Figure 17-67. 332 HyperCard's Authoring Environment ': Mi 1 ■ Figure 1 7-68. n r — T 1 1 L _ -1 c3 ■ t ■ •li; 5. Select the Rectangle tool from the Tools palette (Figure 17-68). 6. Carefully position the cross-hair cursor in such a way that the single-thickness outline of the background button outline is under the middle lines of the cross hair, as shown In Figure 17- 69. 7. Drag a small rectangle in such a way that the three-pixel- thick border of the new rectangle overlaps the background rectangle on the center hne of the new rectangle. See Figure 17-70. 8. Exit FatBits. 9. Choose Select from the Paint menu or type S if you have Power Keys in force. '* Either action selects the new rectangle. ' — 10. Choose Copy Picture from the Edit menu (or type Command-C]. 1 1 . Advance to the next card and choose Paste Picture from the Edit menu (or type Command- V) . This pastes the rectangle atop the M button of the Tuesday card. 12. Choose Transparent from the Paint menu, or type the T Power Key. 1 3 . While the square is still selected , drag it to the T button graphic and place it directly overlapping the background graphic out- line, as you did for the Monday button, 14. Advance to each of the next cards, pasting the rectangle from the Clipboard into each card and dragging the rectangle to the appropriate button graphic. Remember: only one highlight rectangle per card. Building a HyperCard Stack 333 4 File Edit Go Toals Paint Options Patterns Figure 1 7-69. ■is:- ra |Hr-i f-iiiiiiiiiiiii[iiiif!iiPf[[!fiSB[;iii;Effi ■■■■■■■■■■■■a o Rgure 1 7-70. 334 HyperCard's Authoring Enuironment 15. When you've finished with all seven buttons, hold down the right or left arrow keys to cycle through the stack. Ideally, you should see the eflfect that the heavy highlighting rectangle has as it Inches its way down the row of buttons smoothly with the , , ...^ „ change of each card, ' ' y> V The next step is to enable the links between the daily buttons and the cards in the To Do stack. LINKING THE BUTTONS AND CARDS By making the dally buttons background buttons, we can make all necessary links by using the Link To... button for each of the seven buttons. You can begin carrying out the following steps from any caid i« JSiftVi in the stack. . ^ 1. Select the Button tool from the Tools palette. i 2, Double-click on the Sunday button and then on the Link To.., button in the Button Info dialog box. The mini window will appear with instructions to bring the destination card into view. 3 . Use the keyboard's left and right arrow keys to bring the Sunday card into view (the one with the word "Sunday" in the card layer graphic). - ' 4, Click the This Card button on the mini window. This action writes the script for the Sunday button; that is, every time you click on this button, it will bring the Sunday card Into view, as you would expect. 5. Continue double-clicking on each button and repeating the Link To. . . mini window technique. A*-»vv - - Before clicking the This Card button in the mini window, be sure you are viewing the card whose daily button you're editing- the Monday card for the M button, and so on. 6. When you're finished making the links, select the Browse tod r -r -js-is; daily buttons. Click them at random, checking your results with the expected ■ results. If you click a daily button and get the wrong day, then somewhere you erred in establishing the link. Try it again. —V A final graphics task is to fill in the grey pattern around the card, 1. Double-click on the Paint Bucket tool in the palette. This action brings the pattern palette into view. Building a HyperCard Stack 335 2. Select the grey fill pattern Immediately to the right of the black pattern (Figure 17-71), 3. Choose Background from the Edit Menu. ' 4. Click the Paint Bucket's hot spot in the white areas surrounding the card. It may take two or three fills, depending on the pixels you erased in the early stages. 5. Choose Background again to leave background editing mode. We now come to the last construction task, which is to create an icon button linked to the To Do stack. MAKING A STACK BUTTON For a stack like a To Do stack, to which you may wish to refer from other stacks, you should create a button of some kind. That way you can copy the button and paste it in any other stack for an instant switch to your To Do stack, 1. Type Go tojirst card into the Message Box and then choose Background from the Edit menu. < File Edit Go Tools Point Options Patterns To Dci Monday rsFirniiflirwirmi ® H HE -h r—1 L _^ o m T^H ■ ■ \^ -^Phi r □ o 1 == : HO AO a Figure 17-71. 336 HyperCard's Authoring Environment Choose New Button from the Edit menu. A default button appears In the center of the screen, already selected. 3. Double -click on the new button to bring up its Button Info dialog box. 4. Change the name to "My To Do." 5. Click the Icon... button and select the HyperCard stack icon. ^ , CUckOK. I ,. . 6. Double-click the new button again to bring up its info box. 7. Click the Transparent style button. 8. Click on the Link To... button. 9. Click the This Stack button in the mini window. Until you can write a more complex script, this icon button wjj : k ! ' -f open the stack and show the first card of the stack, Monday's, '* ^ 10, Back in the card background, grab the lower left comer oft selected new button and resize it so that the icon is cleart? visible (Figure 17-72). 1 1 . Drag the button to an unused area of the card. 12. While the button is still selected, choose Copy Button from the Edit menu (or type Command-C}. -^^ 13. Using the Browse Tool, maneuver to whatever stacks . wish— the Home stack is a good place to start— and choo tfM Lp ': ' Paste Button from the Edit menu (or type Command- V). - ' — This pastes a copy of the To Do list Icon, complete with Iti linking script to the Monday card in the stack. You're finished with the new stack. We hope you found it fun anc ! Inviting. We also hope you thought of other ideas and variations ymi ■ would like to Include in your own edition above and beyond this exercise. Feel free to explore and experiment at your own pace. Figure 17-72. BuUdir^ a HyperCard Stack 337 Using the Stack Now that the stack is complete, you may begin using it. Into the left column, type activities that should be accomphshed on a specific day. Put longer-term projects and goals into the right-hand column. As you accomplish an Item, use the Macintosh text editing tools to erase Its line ftt)m the field. At the end of each day, select the remaining items ft-om the left column and choose Cut Text ft-om the Edit menu. This removes the items from the day's listing and places them Into the Clipboard. Then advance to the next day's card, place the text pointer at the first empty line In the left column, and choose Paste Text from the Edit menu. When you plan a task for a day several days from now, click on that day's button. When the day's card appears, type the item into the appropriate column. It will be waiting there ft)r you when the day comes along, and you carry over unfinished items from the previous day. So far, we've made this stack very functional. But we can also give it considerably more "life" and "intelUgence" with the help of simple scripts written in the HypeiTalk language. In the next part, we begin to reveal the wonders of the HyperTalk language. It will be worth the trip. In Part Four, you'll embellish this stack with some powerful scripts. PART THREE HyperCard's Programming Environment CHAPTER 18 Introduction to HyperTalk The few peeks at HyperTalk you've had so far in this book probably didn't make a lot of sense to you beyond their immediate purpose. For example, when you inspected the left and right arrow button scripts in the last chapter, it was easy to follow our lead. But left on your own, you surely wouldn't have known where to look for these scripts or how to modify them. You'd need a working knowledge of HyperTalk to even know that you could make such modifications. By the time you're finished with this book, you'll have that knowledge, as well as much hands-on experience in making your stacks do far more than Just link card to card. Programming and Personal Computers ' - In the early days of personal computing, in the mid- 1970*s when you could finally buy a fully assembled computer instead of having to build one from a kit, computers were so new that very little applications software existed for them. Even though these computers were meant to get Into the hands of general consumers, there viras little you could do with them. Among the most popular computers of that day were the original Apple II, the Commodore PET, the Radio Shack TRS-80 Model 1, and a host of machines whose makers are no longer In the personal computer business (or in business at all). 341 342 HyperCard's Programming Environment Recognizing that software was an essential ingredient for their customers' enjoyment of tlie iiardware, the computer makers almost uniformly Included a programming language with the computer. Hie idea— presumptuous in retrospect— was that the customer would "roll his own" software. That meant, of course, that learning to program the computer was virtually a prerequisite to making the machine do something other than play the handful of games that began to appear on software shelves. ONCE UPON A BASIC TIME - " ' The programming language that went with most of these machines was called BASIC, an acronym for Beginner's All-purpose Symbolic Instruc- tion Code— a mouthful, to be sure. Compared to many other program- ming languages available at the time, BASIC was easy to learn. But that's not to say that it was a snap to begin writing useful applications. For many people, it was a struggle. Even the idea of having to learn a programming language to use a computer was enough to scare masses away from computers. Today, many noncomputing people still equate using a computer with programming a computer. You, of course, have proven them wrong already, by using a prewritten application like ; HjrperCard to store and retrieve names and phone numbers. ^ Anyway, this tradition of including a programming language with a computer extends all the way up to the IBM Personal Computer, • ■ released to the world in late 1981. When you buy a PC and the traditional operating system software, PC-DOS, you get the BASIC ^' language on the operating system disk (a reduced version is even in a chip on the PC's circuit board). IVIany of the PC's first generation of '[ business software was written In the BASIC supplied with the com- puter. Then came the Macintosh in early 1984. Among the many traditions this machine broke was the one about including a programming language with the computer. A major principle guiding the machine's design was that no one should have to "get his hands dirty" to use a computer effectively. Instead, the computer came packaged with real •. > • productivity software for doing word processing (MacWrite) and graph- ics (MacPaint) . At the time of release, the Macintosh had only two other software packages available, the Multiplan spreadsheet and, you guessed it, BASIC. The BASIC, however, didn't really let even expert- <.h enced BASIC programmers reach Into the Macintosh's bag of trlclis (called the Toolbox) for doing pull-down menus, standard file dialog u ' boxes, and the like. The user community had to wait for commercial programs to be delivered— a waiting game that lasted longer than earl)' Macintosh buyers care to recall. Introductk>Ti to HyperTalk 343 Today, the wait for quality commercial programs is long over. The catalog of Macintosh software is quite extensive, ranging from easy-to- learn starter programs, like Microsoft Works, to heavy-duty offerings in desktop publishing and three-dimensional engineering graphics. In fact, devoted Macintosh users consider the software offerings for the Macintosh family to be superior to those in the MS-DOS world. While I'll leave the resolution of that contention to the pages of computer magazines, one thing is definite: The consistency of the Macintosh user interface has allowed the user community to focus more on what a software product does rather than on how to use it. THE MACINTOSH AND GREAT EXPECTATIONS As a result, Macintosh owners have a generally higher expectation of what a software program should do for them. The challenge that software developers have. then, is to make software that is almost Infinitely flexible, to accommodate the whims and desires of each user. Ttiis largely flies in the face of software development of yore, in which the program designer imposed a way of doing things that the user was forced to accept. By and large, Macintosh owners won't stand for that. At the same time, more Macintoshes are getting into the hands of people who have very special information-handling needs for the machines- needs that may appeal to too small a group to attract commercial programmers. There are plenty of general-purpose data- bases and spreadsheets out there. But what if your company or department desperately needs training software customized for com- pany policies and procedures? Or what if you want to design a computerized, fully cross-referenced catalog of your company's prod- uct line for telephone salespeople to use as a reference? Prior to HyperCard, the answers to those questions would entail the hiring of experienced Macintosh programmers who could design cus- tom applications from scratch. As any Macintosh programmer will tell you, writing a Macintosh application is not as easy as writing programs for computers like the IBM PC. More forethought and care must go into the program design to meet the userTriendly expectations of Macintosh users. With HyperCard, however, many custom information-handling needs can be met by designing HyperCard stacks. To give authors additional flexibility and power in stack design, HyperCard includes the HyperTalk language, with which you can automate a number of HyperCard processes for yourself and others. In one way, the inclusion of HyperCard with every Macintosh revives the tradition of supplying a custom development tool with the com- puter. But in the tradition of Macintosh's "clean hands" philosophy, 344 HyperCard's Programming Environment HyperCard and its HyperTalk language are substantially easier to . master than other customizing environments, like BASIC, despite the - . overall complexity of designing for the Macintosh. PREPROCESSING The feature of HyperCard and HyperTalk that makes authoring for the Macintosh so much easier is that a great deal of the concems that sidetrack professional programmers have already been covered foryou. A good example is the concept of the screen button. In a traditional programming environment, much planning goes into the inclusion of a button on the screen and its corresponding action when someone clicks on it. While a programmer would have to painstakingly determine .'. . the screen coordinates for a button on the screen, a HyperCard author :'j ! simply drags a selected button on the screen and adjusts its size with • -.T the cursor. The thought of the button's coordinates needn't ever cross the author's mind- although HyperCard is working diligently behind . . the scenes recording screen locations and many other properties of the ■; - button. In a sense, HyperCard is your partner: It preprocesses aL the gobbledygook out of sight. A Word to Experienced Macintosh Programmers: Even the event loop is preprocessed for you in HyperTalk. HyperCard does aH the trapping for keyboard and mouse events for you, including routing to the correct button handler when a mouse event occurs inside a button's rectangle. Most of what you program in Hyper- -,: Talk are button and other object-handler routines. As you may have deduced, it is difficult to discuss HyperTalk ■ • separately from HyperCard . They are Intricately intertwined. While you can use HyperCard and even create a HyperCard stack without writing , , a word of HyperTalk, you can't work with HyperTalk without Hyper- . , . Card. HyperTalk is not a stand-alone language like BASIC, Pascal, or (.:;■ C. It is the language solely of HyperCard, operating on HyperCard . ;'i objects and on the information they contain. Unlike a stand-alone language, you don't use HyperTalk to create stand-alone programs, HyperCard stacks are like tapes that run on the HyperCard player. HyperTalk gives you the power to customize a stack— give the stack more information-handling power than it can ; . acquire on its own. In other words, you can use HyperCard without :' . HyperTalk to link and search for information; if you want to manipulate : .. . i ,! the information in any way— to bring it to life, as it were- HyperTalk is there to follow your bidding. . ■ The language was painstakingly designed to be easy to leam and use, 'my'- The goal was to put powerful authoring tools into the nontechnical fi I While we're discussing HyperCard screens, you should also plan > 1 around the HyperCard structure that prohibits the display of more t than one card on the screen at a time. A HyperCard card occupies the I 1 entire HyperCard window, no matter how sparsely you design the \ i card's graphics and objects. With some clever design work, however, ■ ^ you can simulate the display of a small window atop a card. We'll show you how to do that in a later chapter. These limitations shouldn't prove to be too burdensome, particularly ; with the amount of things you can do with HyperCard and HypeiTalk. , With Uie bit-mapped graphics design power at your bidding, and ^ HyperCard's inherent speed in linking cards and finding information, - you'll be able to simulate most of the Macintosh user interface features ' you've come to know and respect. The challenge of building familiar looks with the tools of HyperTalk is half the fun. HyperTalk Modularity . , = . ; ' Writing HypeiTalk scripts is different from traditional computer pro- ■ " grammlng in many ways, but the most obvious difference Is In modularity. The program listing in languages like BASIC, Pascal, orC can be printed out and studied almost like a word processing docu- ment. To get the computer to follow the Instructions in the program, the user "runs" the program. As the program runs, the computer follows the instructions in the designated sequence (the precise sequencing varies with the language). The program is self-contained. It has a begirming and an end. ' Programming in HypeiTalk is very different. There is really no such thing as a HypeiTalk "program" that controls the activity in a stack from ! . beginning to end. Instead, HyperCard objects (stacks, backgromids, j ) cards, fields, and buttons) contain short scripts, which HyperCard foUovra whenever events occur that affect those objects. For example, you may want HyperCard to retrieve information from a stack's Intrcxluction. to HypetTalk 349 Preferences card each time you create a new card in that stack. Or you may wish HyperCard to place the current time and date in a field when you click on a button. The Instructions for each of these actions should be placed In short scripts attached to the appropriate objects. There- fore, when you create a new card, HyperCard looks into a background or stack script for Instructions to follow whenever a new card is created in that background and stack. Similarly, when you click a button, HyperCard looks into the button's script to find out what to do each time you click that button. A script comes to life only when called upon bv HyperCard. You need write scripts only for the actions you want the stack to respond to. If you don't want anything special to happen when a new card is created, don't write a script that responds to the creation of a new card. HyperCard will simply create a new, blank card and wait for your next keyboard or mouse action. A script is entered, inspected, and edited in a special dialog box called the Script Editor, which is accessible for every kind of HyperCard object: buttons, fields, cards, backgrounds, and stacks. Each object has its own script (or no script). Therefore, If you have card domain buttons that are supposed to behave differently on each of forty cards, you can write forty different scripts, one for each button. Knowing which object to attach a script to requires some thought and awareness of the HyperCard concept of hierarchy, which we'll cover in chapter 19. The value of HypeiTalk scripts being so modular and spread out among so many objects in a stack is twofold. First, it makes It easier to test each script module while you design the interaction of various objects in a stack. Second, you can add features at a later time without having to rewrite or modify an entire program, as in a traditional computer program. Often, added features require little more than modifying a single script or adding a script segment to an object. AU in all. it's a sensible system that makes learning HypeiTalk far easier than other languages. Using the Script Editor ' nie HyperTalk Script Editor is a self-contained environment for working with HypeiTalk scripts. It features a large box in which you type and edit the text that comprises HyperTalk scripts. Although the Edit menu is not available while you use the Script Editor, you can still use Cut, Copy, and Paste commands via their keyboard equivalents Command -X, Command -C. and Command -V, respectively. You select text for cutting and copying, Just as you do In any Macintosh text- editing environment. The content of the Clipboard stays active when 350 HyperCard's Programming Environment you leave the Script Editor, so you can copy and paste scripts from one . . ; object to another. ' ' u While you are In the Script Editor, you may use the keyboard arrow i keys to move the cursor one space in the direction of the arrow. It is ^ , u ' often more convenient to shift the cursor a few spaces with the ' ; keyboard than to use the mouse. : I . . . A HyperTalk command line can be any length, including longer than : : , •: the width of the Script Editor window. Since a command line ends with l ,r:i 8l carriage return (a press of the Return key), you don't want to press • Return until you have finished the entire command line. If you wish to j J, break a long command line in the middle, however, you can type / ^ Option- Return to place a "soft" carriage return in the line. The Script Eklitor places a special symbol ( -■ ) to indicate the soft return, and the text on the next line is automatically indented to match the first hne, Use soft returns to break up long lines where you want them broken, .1 to improve script readability for later editing. i c, To search for a word in a script, click the Find button in the Script | •: Editor dialog box, or type Command- F. A smaller dialog box appears, i ■ ; : requesting that you type the word or string to find. When you press the Return key, HyperCard finds the first occurrence of that string after the V , location of the flashing text insertion potnter . Type Command-G to find , , the next occurrence. You may also select a chunk of text in the script i-r- window and copy it into the Script Editor's find string by typing i Command-H. This action also finds the next occurrence of that string, Continue pressing Command-H or Command-G to keep finding addi- i . tional matches. You may print a script from the Script Editor by clicking the Print button or typing Command-P. If you select a portion of the script ilrst, only that portion will print. The printout contains a page header listing , r i; . the current date and time, plus the name of the object whose script you t ; " are printing (for example, script of card id 2379 = "Setup Card"). If you have been editing a script and decide you'd rather return to the original version, click the Cancel button. If you click the OK button or press the Enter key, HyperCard accepts the current script as it stands f and automatically saves it to disk. I - ■ ■ • - ' i Structure of a Script " V ?: ; ' . ., By now you've probably seen enough scripts to get some notion about ■ >? : the way a HyperTalk script is structunsd. Remember, when we say ^ ; i,. "script" we mean Just a short series of instructions that HyperCard I : )- 1 carries out as the result of some kind of action. | The way you let HyperCard know that it should cany out instmctions | upon a particular action is to virtually say, "Hey, HyperCard, when you [ Introduction to HypeiTalk 351 encounter action A, carry out the following instructions." HyperCard duUfully monitors every acUon that takes place on the HyperCard screen and In the Macintosh system. For every action it encounters, it looks for a script starting with the name of that action. If it doesn't find any such script, it Ignores the action and waits for the next one. This search for a matching script takes only a tiny fraction of a second, so there Is no speed penalty when HyperCard finds no scripts for Its many actions. If HyperCard does find a script, It follows the Instructions entered there by an author. When the script ends, HyperCard returns to its vigilant monitoring of actions. The task of the author, then, is to let HyperCard know on which actions to detour into an instruction list. The mechanism for catching HyperCard actions Is to begin a script with the word "on," followed by the name of the action (we'll see what the standard actions are in the next chapter). You've already seen that to alert HyperCard to go to a different card at the click of a HyperCard button, the button's script begins as follows: ■ ^- 1* on mouseUp That tells HyperCard to foUow instructions on succeeding lines of the script whenever the user releases the mouse button with the Browse tool atop the button. A script needs an ending, too, because an object may have more than one set of script Instructions etched to it. For Instance, an object may have two different scripts to be carried out as the result of both a press and a release of the mouse button. The two scripts would start "on mouseDown" and "on mouseUp," respectively. To keep the instructions in these two scripts separated from each other, each script ends with the word "end" and the name of the action that started the script In the first place. Therefore, the last line of a script that begins "on mouseUp" would read: end mouseUp Now when HyperCard beghis carrying out the instructions in the "on mouseUp" script, it will know when to stop. Without the "end" marker, HyperCard would try to continue on to the next script, carrying out instructions It should not be doing. To sum up, each script must begin with an "on" statement and finish with an "end" statement, as follows: on [action] ^ Instruction 1 Instruction 2 " lie; /iro/'Ki Off: ''< end [action] 352 HyperCard's Progranuning Envtrorunent The "on" and "end" statements in a HyperTalk script are always at the left margin of the script. Instructions between those two points are Indented, Fortunately, you won't have to worry about the formatting of HyperTalks scripts. As you type lines of script into the Script Editor and press Return at the end of a line, HyperCard automatically formats the script for you. You may also press the Tab key at any time to adjust the formatting. As your scripts become larger and more complex (with multiple levels of indentation), the Script Editor's automatic formatting wHl help you know when you closed all the potential loose ends of such a script. Pieces of a HyperTalk Script So far. we've been talking about "actions" as the triggers of scripts. We've been using that term as a matter of convenience, since it is fairly easy to visualize a HyperCard action as being the result of a physical V : action, like pressing and releasing the mouse button. There are more . accurate terms to describe these actions and the other elements of a HyperTalk script. We'll introduce you to them in this section. It's important that you grasp their meanings and feel comfortable with the Vi. terms. The remaining chapters assume a familiarity with these terms, OBJECTS v..*.--i, ;.o«.ht,,-r. I/. f f ! ; f We've had quite a number of dealings with the five basic lands of items in HyperCard: the button, the field, the card, the background, and the stack. To HyperCard, each of these items is known as an object HjrperCard objects are the familiar "things" that you work with, either as a browser or author. You may not be able to physically touch a HyperCard object, but each kind of object has a certain three-dimen- sionality to it that lets your mind grasp it. To help you visualize the relationships among the five HyperCanl objects, we'll present an extended metaphor. First we'll set the scene of the metaphor and, later, apply HyperCard obj ects to the various objects In the metaphor. Imagine a large, multilevel building designed as a hotel. Each of the building's levels consists of a long corridor with doors leading to many rooms. TTie rooms on a given level are identical in shape, color, furnishings, and furniture arrangement. All rooms on one level, for Instance, may have beds for one person per room. A different level has rooms designed for two people per room. While all the rooms were Introduction to HyperTalk 353 designed to be identical, occasionally one room will have an added feature, like an extra light switch on the wall or a folding bed tucked away in the closet so that an extra person can sleep there. But by and large, the rooms are the same. The only thing that differentiates one room from the next on the same floor is its room number and the person who sleeps in the bed(s). Once the hotel is built, all the action takes place In the rooms, notably who's sleeping In the beds on any ni^t and what happens when switches are pressed. ir.: utij > ^ The analogues to HjrperCard objects can be summed up as follows: Hotel Building Stack Floor i-^wi. Background Standard Bed Background Field Standard Switch Background Button Room : 0 Card Extra Bed Card Field Extra Switch Card Button Room Occupant Information -!i : r., ; Now lefs examine these relationships in more detail. A HyperCard stack is an all-encompassing object. That is, the stack consists of many pieces (other objects). Just as the hotel building consists of various building blocks like floors, rooms, and beds. A stack, of course, Is much more easily modified than a concrete bufldlng. You can add backgrounds, cards, and other objects to it at any time. The main point is, however, that if you wish to find a piece of information, you must know the stack in which it resides. In the hotel metaphor, if you were looking for an overnight guest to your town, it wouldn't help to know only his room number or name. You must know which hotel he's in before you can start looking up a number or name. There may be twenty hotels in town with a room number 20 1 , But there's only one hotel with your friend in its room number 20 1 . And what distinguishes one hotel from others— at least in the sense of narrowing the search for your friend— is not its contents or constituent pieces, but its name and address. In our hotel, we said that each floor was designed according to a plan that calls for identical rooms for one floor. Hie plan for a floor is very much like a HjrperCard background. The background domain is shared by every card In the stack, just like the room design for a given floor is shared by every room. The color scheme, carpet pattern, room layout, and fumishings are determined by the floor plan. In a HyperCard stack, a background typically sets the scene for a group of cards, complete with forms design, bacltground patterns, arrangement of elements on 354 HyperCard's Programming Environment the screen, and so on. If your stack requires a different arrangement of i~ > elements for a second group of cards, you add a background, just as the br.r hotel might add a floor of differently designed rooms to accommodate ' families in addition to their usual business travelers. • ' ' When the hotel designer planned the rooms, he established the location of the furnishings and electrical wiring. In the design, every room on a floor has a bed in the exact same location. What the plan does not account for, of course, is who will be sleeping in each bed each night. That's no concern of the plans, anyway. All the designer is concerned about is the size, location, and firmness of the bed that goes in each room. The beds can be likened to HyperCard background fields, Properties of background fields are established in the grand design of the group of cards: A field in that background will have the same size, location, and other properties on all cards, as decided tn its background specifications. In the electrical department, the designer specifies that wall switches are installed in the same place In each room. That way, maids and frequent guests wUl know where to reach for lights in any room on the floor. Think of the light switches as background buttons. They're in the [ same place on every card sharing the same background, and the action is the same when you press the same button on every card sharing the ^' background. Perhaps the best way to sum up the background objects in the hotel metaphor is to say that the designer designs a room only insofar as the [: ' room will serve as a model for identical rooms. He doesn't design room ^ 411 specifically, but rather the model for all rooms on the fourth floor. . , , (In truth, a hotel designer is not so ruthlessly cookle-cutter-orlented, but bear with us for a while longer,) Now we tighten our focus and look at an individual room: the card , object hi HyperCard. Just as a hotel room exists for the purpose of 1 housing a guest, so does a HyperCard card exist for the purpose of i- giving Information a place to rest. All empty rooms on a floor look alike. AU empty cards in a one-background stack look alike. You see the buttons and fields, but there Is nothing distinguishing one empty card from another except for its card id. That's where HyperCard has one up on the hotel. The hotel manager is stuck with unsold rooms when no J one checks into them on some nights. He can't delete the room to down on his financial overhead. But a HyperCard stack doesn't n empty cards at all. In fact, you may add and delete cards as informatl "checks In" and "checks out." Textual information, as we've seen throughout this book, is stored only In text fields. In our hotel scenario, you would say that a guest is identified not only by the room number he's in, but also by the bed he's sleeping hi. Remember that the floor plan determines the properties Introduction to HyperTalk 355 the bed, but the bed is only useful when someone is sleeping In It. The same is true for a background field . It is always on the card , but the card isn't productive unless information is in the field. When there are several fields in the card, each is differentiated from the other by an identification number, like beds in a hotel room may be known as "Bed 1" and "Bed 2." E^^ery room on that floor has a Bed 1 and Bed 2, but John Doe is sleeping in Bed 2 of only one room; Sally Roe is sleeping In Bed 2 of another room on the floor. It turns out that there is the possibility that not all rooms on a floor are the same, Just as aU cards of a background need not be completely identical. One room, for Instance, may have a folding bed in the closet. This was certainly not in the floor plan and Is specific only to the one room. In HyperCard parlance, this would be equivalent to a card field: a field you add to the card domain of one card only. Therefore, if the room with the folding bed can house one additional guest for the night, so can your card with the extra field contain one more piece of Information. No other card in the stack will be aware of this extra field. Similarly, if the hotel experiments with a bathroom fan in one room and adds a switch to the wall plate, that extra switch is not in the original floor plan. It is analogous to the card button: one that carries out an action only from the card in which it is placed. You don't see it on other cards, any more than guests in other rooms would see a fan switch on their wall plates. : . ;.:v:.'.r:T r • ■ , - vH ■ We hope you're still with us on this extensive metaphor. The purpose of it all was to demonstrate that HyperCard objects are entities unto themselves yet have complex interrelationships with other objects. Moreover, as we'll see much more in the next chapter, there is a very specific hierarchy of objects. We must make sure that you appreciate the difference between object relationships and the layering principles detailed tn previous chapters. The two subjects are quite separate from each other. Layering is predominantly concerned with the physical appearance of cards on the screen. The object hierarchy operates almost entirely behind the scenes and becomes important to the HyperCard author as he peeks behind the HyperTalk curtain. MESSAGES We'll begin this section with the following statement: HypeiTalk Is built around a system of sending messages to objects. We don't expect that statement to mean too much right now, but when we repeat it at the end of this section, it will make incredible sense. We Just wanted to show you where you're headed before you set out. In the real world of interacting with people, it's quite natural to send messages to another human being. Sometimes messages are written as 356 HyperCard's Programming Envimnment notes or formal letters. Other messages may be sent electronically, like . electronic mail. And still others may be transmitted without exchang- i Ing a single word. A menacing glare can be a potent message, as was | a thumbs down signal in a Roman amphitheater. A message, therefore, ; may be a command to do something {"Do this") or simply a statement i of fact {"It is now 3 p.m."). HyperCard is constantly generating statement-of-fact messages i behind the scenes. Even when you're not touching the mouse or i keyboard and HyperCard seems to be taking a nap, the program Is j generating messages. For example, when nothing appears to be hap- t pening on the screen, HyperCard is generating a message that says j "idle," meaning that nothing else is going on and it is idling, like a car i in neutral. When you press the mouse button, HyperCard yells, \ "mouseDown." When you release the mouse button, Uie message Is "mouseup." These messages are not general broadcasts to the world. They are addressed to specific recipients, each of whom is a HyperCard object, Exactly which object is the addressee depends on factors such as the nature of the message and how it was sent. We'll look more closely at "who gets what" in the next chapter. As you'll recall, a HyperTalk script is attached to a particular object, like a button or a card. The script's underlying purpose is to intercept a HyperCard message. When the script identifies a message addressed • to its object and its own script name, it directs HyperCard to follow instructions in the script. A script that reacts to a message is officially called a message handler. When the script intercepts a message, It handles the message accordingly. Technically speaking, a script may contain one or more message handlers; the script, therefore, is every- thing you see in the Script Editor window. Let's visualize the mechanism that generates messages and what happens when a script intercepts one {this is simplified for our first excursion behind the script scenes— more detailed explanations vM. follow in the next chapter). In Figure 18-2, HyperCard is meirliy sending idle messages while nothing is happening on the screen. Suddenly, at the press of the mouse button, HyperCard sends a mouseDown message to the button that is under the Browse tool at that Instant. Quickly searching the button object's script for a mouseDora message handler, it finds none and resumes sending its idle message L many times a second. ^ In Figure 18-3, the string of idle messages is interrupted first by mouseDown message, then by a mouseUp message, which come'^l spends to the release of the mouse button pressed Just an instant ago. ■ Tliis time, when HyperCard searches the button's script for a mouseUp H message handler, it finds one. Before HyperCard can resume sending Introduction, to HypeiTcdk 357 idle idle idle idle idle mouseDown no Button Scri pt on mouseUp visual effect wipe left go to next card end mouseUp Figure 18-2. HyperCard continually sends idle system messages until a keyboard or mouse action, such as pressing the mouse button. It sends a mouseDown message to the button clicked on by the user. HyperCard searches the script for a message handler for that message. die die die die ' idle mouseDown mouseup — idle idle idle Button Script II pn mouseUp isual effect uiipe go to next card end mouseUp left Figure 18-3. When HyperCardJinds a matching message handler, it carries out the script within that handler before retuniirig to the stream of system messages. 358 HyperCard's Programming Environment its own messages, It must follow the handler written for it. In this example, It sets the visual effect to the wipe left and advances to the next card. At the end of the mouseUp handler (so noted by the "end mouseup" notation at the hander's conclusion), HyperCard resumes its idle message generation, waiting for some future action to trigger the same or a different message. Now, HyperCard isn't the only message creator In town. Each instruction line of a HyperTalk handler is Itself a message- usually a command kind of message. In other words, scripts also send messages, Recipients of script messages are most often other objects, but not always (don't worry about the latter qualification until the next chapter). In the case of the messages in the mouseUp handler in Figure 18-3, both messages eventually find their way to HyperCard itself, which knows how to process the Visual Effect and Go messages, as If it had message handlers starting with "on Visual Effect" and "on Go," To sum up the message flow: HyperCard itself sends statement-of- fact types of messages {for example, "mouseUp") to various objects in a stack. Scripts send command-like messages to other objects and to HyperCard itself, the latter for canylng out bullt-ln commands. You can also send an Immediate message yourself by typing it Into the Message Box. You'll learn later that you can Instruct a script to Impersonate HyperCard by sending statement-of-fact messages to other objects— a powerful feature that advanced HypeiTalk program- mers use frequently. Now we can repeat the assertion made at the beginning of this section: HyperCard and HyperTalk are built around a system of sending messages to objects. The more you learn about HyperTalk, the more this concept will become second nature to your way of thinking about HyperCard. COMMANDS Each line of a HypeiTalk message handler, other than the "on" and "end" lines, is an Instruction for HyperCard to follow. All such instruc- tions start with what an English teacher would call an Imperative verb, like the "do" In "Do this," In HyperTalk, these imperatives are called commands, and they tell HyperCard to do something for us. Most commands require additional Information (called parameters] to carry out the command, HjrperCard understands around forty commands (some with mul- tiple forms), which are built into it. They range from navigation commands to arithmetic to information manipulation commands and others. We'll examine each command In detail, starting In chapter 21, Introduction to HyperTalk 359 Since you can send a command message to HyperCard directly from the Message Box, that's a good place to experiment with commands. Let's try some. Our first experiment will be to issue a command that brings into view the card following the one you're looking at. We'll use the Go command along with parameters that let HyperCard know where it should go. Since HyperCard understands the phrase "next card" as a legitimate place to "go," that will finish the command. 1. Open any HyperCard stack, making sure the Browse tool is selected. , 2. If the Message Box Is not visible, press Command-M or choose Message from the Go menu. 3. Type go to next card into the Message Box and press Return or Enter. -.r. HyperCard dutifully obeys your command message and brings the succeeding card into view. Since the message stays in the Message Box, you can press Return or Enter a second time to advance one more card through the stack. HyperCard is pretty smart, because it knows that when you issue the Go command and an adjective like "next" or "previous," you can only be referring to cards. While you can Go to a different stack, there is no real next or previous stack. Only next and previous cards. Therefore, if you type only go to next into the Message Box, H3rperCard knows you meant go to next cartL Try it. What happens if you issue a command that HjrperCard doesn't know? In return, it presents a small dialog box telling you that it doesn't understand the particular command (Figure 18^). Try typing Flub next into the Message Box and pressing Return or Enter. HyperCard won't understand the command Flub. Can't understand flub - J*. ji'.' i-^ [ Cancel | Figure 18-4. When HyperCard doesn't Jind a handler for a message, it tells you it can't understand that message. 360 HyperCard's Programming Environment A command, then, is the first word of a message, whether the message is in the Message Box or in a script. A more advanced feature of HyperTalk, as you'll learn in the next chapter, is that you are not limited to the command vocabulary of HyperCard . The language is extensible, which means you can add commands to HyperCard as you see fit. As complicated as this may sound, it is no more complex than writing a script whose "on" word is the name of the command you're creating. FUNCTIONS ^- — >i->:^i;-- •• r - n - - > t. i ' There are times in a HyperTalk script when you need some information about the condition of the Macintosh system. For example ifyour stadt Is supposed to place today's date Into a field of a new card, you need a way to fetch the Macintosh clock's date. Or If you wish to have two different actions result from the click of the same screen button, you may want the button's script to carry out different commands when the Option key is pressed along with the mouse button. You need a way to "read" the Macintosh keyboard to see if the Option key was pressed ■ concurrently with the mouse button. In both cases, you summon HyperCard fimctions. ' It's easy to mistakenly conceive of a function and a command as being Identical when you experiment with functions In the Message Box. You can type a function name Into the Message Box and press Retum, just like a command. The most visible difference between a command and ' a function, however, is that a function always comes back with some kind of answer or reading from the depths of the computer. Program- mers often refer to this handing back of information by saying that a function "returns" or "gives" an answer. Therefore, the HyperCard the time function returns the time from the system clock. Although we're ' not trying to turn you into a computer hacker, the "returns" designation works well within HyperCard, so we'll use it frequently. After all, you send a function to HyperCard, and it returns an answer to you, To see how this returning business works, we'U take the simplest example— typing a function into the Message Box. In any HyperCard stack, make sure the Message Box is showing. Then type the date Into the Message Box. The instant you press Retum or Enter, HyperCard replaces the function name with the date it finds In the Macintosh « internal clock (Figure 18-5). - This Instant replacement is a key property of a function. The function name [the date, in the above example) can be used as the equivalent of the value returned by that function. If we had a script whose duty was to place today's date Into a field on a card, the message the script would send to HyperCard would be put the date into field I. When HyperCard encounters the function in the message, it automatically supplies the Introduction to HyperTalk 361 the date 5/2/38 Figure 18-5. Functions return a calculated value in place of the Junction name. current Macintosh clock's date for the function itself when It follows the instruction. The result, therefore, is that the actual Macintosh clock time is put into field 1, not the words "the date." (If you wanted to put the actual word into the field, the message should read put "the date" into field 1 , the quote marks indicating a text string as opposed to a function.) As a rule, then, you place a HyperCard function in a message where you wish to insert a reading from inside the Macintosh, like polling the clock or special keys on the keyboard. There are a few other types of functions, which we'll examine in full detail in a later chapter. PARAMETERS /' ^ You've already been introduced to the idea of parameters— modifying words or numbers following a command or function, and separated from the command by at least one space. The parameters you saw in the Go command acted like adverbs to HyperTalk command verbs specifying where to go. One command that drives home the idea of parameters quickly is the beep command. The beep command accepts a number as a parameter to instruct HyperCard how many times to sound the Macintosh beeper. In the Message Box type beep 2. When you press Return or Enter, the machine beeps twice. Now type heep 5 and press Return or Enter. The machine beeps five times. TTie number is a parameter (also called an argument). Functions can also have parameters. For example, the number function can reveal a great deal of information about the number of buttons, fields, cards, or characters, depending on the parameter after the function name. If you type the number of background buttons into 362 HyperCard's Programming Environment the Message Box, HyperCard returns a count of the background buttons in the current card. Type the number of cards, and HyperCard returns a count of the cards in the current stack. for some commands, parameters are optional. Beep, for instance, can stand alone, signifying that a single beep should result; but add a number as a parameter and multiple beeps wUl result. In the chapters that detail the commands and functions built into HyperCard, all possible parameters wHl be spelled out. VARIABLES ' T 7, ^ ' , In long scripts, it often becomes necessary to place text or numbers In a temporary holding place while the script performs another action, If you've ever assembled a toy model or kit, you may recall a phrase like, "Set this subassembly aside for use later." That is often the case in a HyperTalk script (or any computer program, for that matter). These temporary containers are called variables. • - ' You can experiment with variables from the Message Box, although • f most of your variable work as a HyperCard author will be in HyperTalk scripts. In the Message Box type put "hello " into greeting. This command ■ places the text "hello" into a variable container called "greeting," You didn't have to do any preparation to use the variable name. By simply telling HyperCard to put something into a container with a name HyperCard didn't recognize as an existing object, HyperCard automati- cally created the variable with that name. Once you've placed something into a variable, the variable name can be used to stand In for its content in a command hne. Therefore, if you type greeting into the Message Box, HjrperCard understands you to mean that you want the content of the variable called "greeting." It places hello tnto the Message Box in return. Even though the variable showed you its content in the Message Box, the variable still contains the tnformation stored in It. Prove it by tjrping greetm^ into the Message Box again. For this kind of variable (that is, one generated In the Message Box), the variable wiU be active as long as you don't quit HyperCard. When you quit HyperCard, the variable is erased. ' ■ ■ In the meantime, however, you can freely change the contents of the variable. If you now type put "good-bye' into greeting, the original contents are covered by the new phrase. Type greeting into the Message Box to show that the variable now contains the phrase good bye Unlike the shenanigans of many computer programming languages, " you can use most variables in a HyperTalk script without warning HyperCard that you're going to use them. Nor do you have to declare that a variable will be used for a number or text (HyperCard treats every cheu-acter as text, although it knows by certain arithmetic commands IntmducOon to HyperTalk 363 to convert text digits into numbers for math manipulations). Not only that, but you can give any name you wish to a variable when you store something in it— as long as the name is one word. This gives you the flexibility of assigning names to variables that mean something to you while you're writing the script. Let's look at an example. Suppose you're performing a string of calculations, such as adding the contents of three fields to achieve a total. The total number will eventually go Into the fourth field on the card. The addition Is performed as the result of clicking on a button labeled "Add." The script that performs the addition, then, would be attached to the Add button. To accomplish the addition In HyperCard, the HyperTalk script will fetch the iirst number, store It in a variable, and then add each of the second and third numbers to the variable. Once the addition is completed, the contents of the variable will be placed Into the fourth field, where the total should go. The script Is shown below: on mouseUp put field "first number" into holder add field "second number" to holder " > - ' ; ^ add field "third number" to holder '' ' ' ' i' ' ' put holder into field "total" ' " ■ end mouseUp * . ' . • In the first message, HyperCard retrieves the content of the field named "first number" and places it Into a variable called "holder." Therefore, tf you had typed a 10 into the first field on the card, the variable holder would contain the number 10 after the first message of the script. The second message performs some arithmetic. It fetches the content of the second field and adds that to whatever Is in the variable "holder." We noted earlier that the numbers In fields and variables are actually stored as text. The Add command performs some lightning-fast conver- sions to change the field and variable contents to numbers for the math. Then it stores the result in the variable as text digits. If the second field on the card had a 20 in it, the variable holder would have the number 30 in It after the second message. The third message Is like the second, but it fetches the number from the third field and adds it to the variable. If the third field had a 25 in it, the variable holder would be 55 after the third message. Notice that holder's content varies with each message— hence its designation as a variable. Once the arithmetic is finished after the third message, the handler can now place the content of the variable into the fourth field on the card, named "total." To do this, the handler message simply places the variable— remember, HjrperCard interprets the variable's name as 364 HyperCard's Programming Environment ■ ' meaning the content of the variable- into the field on the card. By the ■y.o i<; : end of the handler, HyperCard has placed the 55 Into the total field. '» . ! ■ An interesting property of regular variables like holder, above, is that • u they exist in memory only during the running of the handler that mentions them. In other words, the minute the handler finishes. ' . ' ; HyperCard has no recollection of any variable named "holder," There- r v2 fore, If you ran the handler and then typed "holder" into the Message • -:riv Box. HyperCard would say it doesn't understand holder: It finds no h r' j '. variable, command, or function with that name. The upside to thtete that you can reuse variable names in every handler without fear of HyperCard accidentally using the content of a variable activated <,,:^"; -.< :;'>jjs .s'^,;U.?v»'j;^-: : 'fr V Button Script r on mouseup go Home — end mouseUp HyperCard I Home Stack t Stacic Background t Card Z3 Button Field I Figure 19-7. The Home button's script sends a gd message, which starts at its own level and works its way up to the HyperCard object, since no other script aSong the way trapped for go. > , - , 376 HyperCard's Programming Environment >- ir to the Index button object. With this script in place, the message path looks like that in Figures 19-^ and 19-9. .(,7;.:o . Notice one important concept. The two button scripts, although T ■ trapping for the same message , are entirely separate entities as far as , ^, HyperCard is concerned. In other words , when you click on the Home button, the mouseUp message goes only to that button (at first). No other obj ect at the same hierarchy level— buttons, here— ever sees that message. All scripts and properties of an object are private to that object, shared by no other object on the same level. Message Entry Points " " * ' By now you may be wondering how HyperCard knows where to send messages, such as mouseDown and openCard, Not every HyperCard message starts at the button or field level in the object hierarchy. For example, it wouldn't make any sense to send an openCard message to a button. HyperCard sends the openCard message the histant you bring a card into view. If there were more than one button on a card, to which button would HyperCard send the message? There would be no way for HyperCard to know, and it would be a waste of time to send messages to them all. No, the most logical place for the openCard message to start its way up the hierarchy Is at the card level. The place along the hierarchy at which HyperCard sends a system message is called that message's entry point. Buttons, fields, and cards are potential entry points for certain messages in HyperCard's message vocabulary. In other words, HjrperCard sends some messages Initially to one object, other messages to another object, and so on. Messages then continue up the hierarchy until they are trapped by a script or HyperCard itself. If system messages make it all the way to HyperCard without being Intercepted, no action results from the message. Listed below are all the messages that HyperCard sends and their entry points. Since HyperTalk does not distinguish between uppercase and lowercase letters, the capitalization scheme in the following list is not of critical importance. Still, a recognized convention of beghiningall names in lowercase and capitalizing the first letter of the second and third compound words makes scripts quite readable. We urge you to follow this convention. We'U examine the nature of the messages in the next section, but for now, see if you can make out a kind of pattern in the messages and thdr initial destinations along the hierarchy. J:0 ■■. Messages, Hierarchy, and Inheritance 377 4^ ^ t£vjr' izzizi:: 1 C«rd I Index Button Script tiiDuseUp -^^^^^^^^ go to first card end mouseUp Button mouseup Figure 1 9-8. The Index button s script traps for the mouseUp message when the user cUcks on the Index button. HyperCard t Home Stack I Stack Background Index Button Script I on mouseUp go to first card- end mouseUp Card Button Figure 19-9. The Index button's script sends a go message (although with d^erent parameters than the Home button's go message), which wends its way up the hierarchy to the HyperCard object. 378 HyperCard's Programming Environment To Button: newButton, deleteButton ' mouseDown, mouseStillDown, mouseUp mouseEnter, mouseWithin, mouseLeave To Field: newField, deleteField ' openFleld, closeField mouseDown, mouseStillDown, mouseUp mouseEnter, mouseWithin, mouseLeave To Card: newCard, deleteCard openCard. closeCard newBackground, deleteBackground openBackground, closeBackground ■ ; newStack, deleteStack openStack, closeStack mouseDown, mouseStillDown, mouseUp retumKey, enterKey, tabKey, arrowKey suspend, resume, startup, quit help, idle, doMenu Until we get to the meaning of these messages, we should explain one point about the above listing. You may be wondering how HyperCard can send the same messages (mouseDown, mouseStillDown, and mouseUp) to three different objects as "initial" destinations. TTie answer to that question revolves around the location of the Browse tod when the mouse button is pressed and released. If the tool is atop a button of any kind, HyperCard sends the message to that button; If the tool is atop a text field, the message goes to that field initially; and If th: cursor is atop neither a button nor a text field, the mouse messages^ to the current card. By following the rules of H5rperCard hierarchy, then, you can different mouseUp message handlers in a button and in a card background, for Instance, as we did In the recent example. CUckingon the button causes the button's mouseUp handler to work Its magic; clicking elsewhere on the card causes the card or background mouseUp handler to execute. A HANDS-ON EXAMPLE Since you've already been introduced to the mouseUp message, foil along in an experiment to demonstrate how the hierarchy of messages works. To help signal the location of various hierarchy levels when a mouseUp message is handled, you'll use the HyperTalk Beep com- . ,. mand. This wUl give you an audio clue as to what's going on Inside the HyperTalk scripts. Your first group of tasks includes setting up the visual environment of the experiment. Messages, Hierarchy, and Inheritance 379 1 . Prom the Home Stack, pull down the File menu and choose New Stack. 2. At the dialog box, type In a stack name, such as "Beeper" and press Return. The new stack looks like an empty Home card. ' 3. Select the Field tool In the Tools palette. ^ The outline of the background text field appears, 4. Double-click on the field to bring up its Field Info dialog box; select shadow style; select Locked Text; and click OK. 5. Resize the field similar to the field shown in Figure 19-10. 6. Hold down the Option key and drag (peel ofl) a clone of the field, leaving it just below the original. 7. Double-click on the second field to bring up its Field Info dialog box; turn off the Locked Text setting; and click OK. 8. Choose New Button from the Objects menu. 9. Double-click on the button to bring up the Button Info dialog box. type "One Beep" into the button name box, and cfick OK. 10. Hold down the Option key and drag a clone of the first button, positioning it on the screen so that it overlaps the original button, as shown In Figure 19-11. B. Figure 19-10. A -^V*' •- 'ir.-'". ' System Messages ^ The messages HyperCard sends to objects— as differentiated from messages sent by scripts— concern the state of the Macintosh system at any given Instant. These messages, therefore, are called system messages. While such messages are most frequently mouse-related, they may also reveal what's going on with certain keys of the keyboard and actions that HyperCard is itself taking, such as creating new objects or deleting objects. We can now examine each of the H3rperCard system messages. We'll look at what goes on to generate them and why they go initially to the objects they do. MOUSEDOWN. MOUSESTILLDOWN, AND MOUSEUP What you probably consider to be one action— clicking the mouse button— HjrperCard sees as three distinct actions: pressing the mouse button, holding the button down, and releasing the button. Each one of those actions triggers a HyperCard message. The instant you press the mouse button, HyperCard sends a mouseDown message to the appropriate object, which may be a button, field, or card, depending on the object that "sees" the Browse tool when you press the button. You would trap for a mouseDown message when HyperCard's Programming Environment you wish to carry out some script when the mouse button Is pressed, but before the button is released. All the while the mouse button is held down, HyperCard sends a j steady stream of mouseStillDown messages to the current object. The | messages come at a pace of many times each second. We cant j demonstrate the exact speed of these mouseStxUDown messages, but | we can show you how to watch the process in action. ' 1 . Create a new button with the following script: on mouseStillDown add 1 to the Message Box end mouseStUlDown 2. Before clicking on the button, show the Message Box (type Command-M) and type a zero Into It. V 3. Press and hold the mouse button with the Browse tool atop the new button. in: Each time HyperCard sends the mouseStillDown message, the button's script traps it and increments the content of the Message Box by one. While the increase of the value in the Message Box might seem fast, ■ it Is really much slower than the frequency of the mouseStillDown messages coming from H5rperCard. Each time HyperCard sends the message, the script must take extra time carrying out the script's commands and displaying the new value on the screen. When It doesn't have to update the screen, HyperCard sends messages many times faster than what you see. . ^ Use the above button and script to observe one additional proper^ of the mouseStillDown message. HyperCard sends the mouseStill- Down message to the same object that received the mouseDom message when you pressed the mouse button. Therefore, if you hold down the mouse button and drag the Browse tool outside the button, the button will keep getting the mouseStillDown messages, and the value in the Message Box will keep Increasing. Conversely, if you press the mouse button outside the button, hold down the mouse button, and drag the Browse tool into the screen button, HyperCard keeps sending the mouseStillDown message to the card, not the button. The value In the Message Box won't budge, even when you drag the tool into the button's region. Therefore, keep in mind that the mouseDown and mouseStillDown messages from a single press of the mouse buttongo to the same object At the release of the mouse button, HyperCard sends the mouseUp message to the current object, provided the Browse tool is atop the Messages, Hierarchy, and Inheritance 385 same object it was at the time HyperCard sent the mouseDown message. On the first pass, this may sound a bit confusing, but as you'll see in a moment, the special behavior properties of the mouseDown message follow exactly the way the mouse behaves in a regular Macintosh application. To demonstrate, we'll look at how items in a typical dialog box respond to the mouse. 1. Choose Page Setup from the FUe menu. You'll see the Page Setup dialog box. 2. Place the arrow cursor atop one of the radio buttons that is not selected (Figure 19-13), but don't press the mouse button Just yet. 3. Now press and hold the mouse button without moving the cursor on the screen. Do not release the mouse button yet. Notice that the inside lining of the radio button has darkened a bit. This is visual feedback that you are about to select this button (Figure 19-14). < ; -v - ; ^ 'kJ . ' LaserUlriter Page Setup Paper: ® US Letter O n4 Letter C^US Legal O B5 Letter Orientatian Reduce or Enlarge: Printer Effects: ^ Font Substitution? n Smoothing? ^ Faster Bitmap Printing? ^0 [ Cancel ] [options] [ Help 1 Figure 19-13. Place the cursor atop one of the radio buttons, but don't press it yet LaserlLlriter Page Setup — ■ • ■ ■■ ■ ■ ■ — ■ 't Paper: (8) US Letter Q H4 Q US Legal O B5 Orientation ' ■i a. ■■ fCi' Figure 19-14. When you press the mouse button and hold it down, the button highlights somewhat, providing utsualfeedback that you. are about to select this button. 386 HyperCard's Programming Environment 4. While still holding down the mouse button, drag the cursor ' away from the button toward the bottom of the screen. The instant the cursor leaves the region of the button, its inside Uning unhighlights, showing you that It will not be selected when you release the mouse button. 5. Now release the mouse button. Nothing changed on the screen, because the mouseUp action took place off the button in which the mouseDown action fi' J occurred. Let's stop for a moment and analyze what happened here in Hypff- Card terms. If this were a HyperCard card, you'd say that HyperCafd sent a mouseDown message when you pressed the mouse button ato the screen button. As long as you continued to keep the mouse buti depressed, HyperCard was sending mouseStUlDown messages to 1 screen button, even when you dragged the cursor away from button. But when you released the mouse button, HyperCard dldn^ send a mouseUp message, because the mouseUp action occur somewhere other than in the object of the mouseDown action. The converse of this relationship is also true. If you press and holdt mouse button with the cursor away from the screen button, and i drag the cursor to that button to release, nothing happens on screen. Try it yourself in the Page Setup dialog box. One beneiit of the mouseDown- mouseUp relationship Is that if j accidentally press a HyperCard button, you can change your mind i drag the cursor off the button before releasing the mouse button. Sln(^ the mouseUp message wiU then not go to the original object (in fa there won't be any mouseUp message), nothing In your stack chang All of this is explanation for the reason behind most mouse-bas scripts in HyperTalk being mouseUp message handlers, as opposed! mouseDown handlers, as you might expect at first glance. Anytime yof write a script that Is to be In response to a traditional click of the mousi button, put that script Inside a mouseUp message handler. HiatJ precisely the behavior found in mainstream Macintosh buttons. MOUSEENTER, MOUSEWITHIN, AND MOUSELEAVE Three other mouse-based messages are directly related to the poslti3 of the cursor on the screen with respect to objects like buttons : fields. HjrperCard sends these messages to buttons and fields whene the cursor enters the object's screen region, while the cursor is in 1 ' ■ region, and when the cursor exits the object's screen region, resp tively. At no time Is the mouse button pressed when HyperCard se 1 ii Messages, Hierarchy, and Inheritance 387 these messages. These are excellent examples of the kinds of messages HsrperCard sends when you believe not much is going on. If you wish to see how these messages work, especially In relation to the mouse button messages described above, place the following handlers into a button script: on mouseStillDown < ■ it ^. add 1 to the Message Box ; £^ v v H end mouseStlllDown n> u on mouseLeave beep 2 r. , . end mouseLeave With this set of handlers. HyperCard will do the following: When you move the cursor Inside the screen button. HyperCard will beep once; while the cursor is inside the button, the value of the number In the Message Box will increase In Increments of ten; when you press and hold down the mouse button while the cursor Is inside the screen button, the Message Box value will increment only by one, since the mouseStillDown message will be sent to the button instead of the mouseWithin message; when you release the mouse button with the cursor still inside the screen button, the Message Box value will return to Incrementing by ten; and when you move the cursor outside the screen button area, HyperCard will beep twice. To gain further experi- ence with the operation of all mouse-related messages, experiment with the above scripts by dragging the cursor in and out of the button with the mouse button pressed. It Is unlikely that you'd put handlers for mouseEnter, mouseWithin, or mouseLeave messages In objects other than fields and buttons, since die cursor can't really "leave" or "enter" a card or background, both of which take up the entire screen. Still, these mouse messages go up the hierarchy just like any untrapped message. NEW AND DELETE OBJECT MESSAGES ' " Each kind of HyperCard object, from button and field through stack, can be created and deleted by various means. As you'll come to appreciate the more you work with HypeiTalk and HyperCard, there on mouseEnter beep 1 end mouseEnter on mouseWithin add 10 to the Message Box end mouseWithin 388 HyperCard's Programming Environment will be times when you will want to trap for the creation or deletion of an object. For example, when the user of the stack creates a new telephone log card, the stack wUl trap for the newCard message and < r, ; insert the current date and time into fields on the new card. Oryou may wish to warn a user that when they delete a button In a stack they should make special modifications elsewhere. Each time a new button, field, or card is created or deleted, Eyptx- Card sends a relevant message of that event initially to the same level as the object that was created or deleted. On creating and deleting backgrounds or stacks, the corresponding messages are sent to the current card. Therefore, when you choose New Card from the Edit menu, HjrperCard sends a newCard message to that new card. In the case of a new object created with a menu selection (for example, New Card, New Field, etc.) , the object won't have any scripts in it to trap for the newCard message, so the handler for that message should go into a higher level, such as the background or stack. But if you clone a field or button (holding down the Option key and dragging a copy from the original), the object can already have a newField or newButton message handler in it to respond to HyperCard's messages. OPEN AND CLOSE OBJECTS ' ' Every object e^rept the button opens and closes. When you click on any text field to insert or edit text, you open that field. If you modify the ; contents of a field and then either select another field or click the mouse outside of the field , you close that first field . Each time you navigate to a new card, you open that card. Proceeding to the next card in the stack : : closes the first card and opens the next one . A background opens when sit . you arrive at a new bacl^ound from a different one. A stack opens ■r -y when you go to that stack; a stack closes when you go to a different stack. rii!. It's not so much that the objects actually open and close as It is HyperCard sending messages Uke openStack and closeField on those occasions. These are system messages, like the others we've been : discussing so far, because HyperCard sends these messages after . reacting to what is occurring inside Hyper Ceird, ^1 : Open and close messages are relatively common In HypeiTalk scripts. For example, if you design a stack that has cards descrlbtag cities around the world, you will want HjrperCard to calculate the current time in the city when you open the card. To accomplish that, you'd need a script that traps for the openCard message. In another common use, a HyperCard stack should restore certain settings when it closes. For Instance, if your stack turns off the menubar when it Messages. Hierarchy, and Inheritance 389 opens (in response to an openStack message), it should show the menus when it closes (in response to a closeStack message) so that the user has menus available when going to another stack. RETURNKEY, ENTERKEY, AND TABKEY HyperCard monitors whether the user presses the Return, Enter, and Tab keys outside of text fields, and sends corresponding messages. As with mouse-related messages, the keyboard messages are not sent when you are editing text in a text field. Recall that In field text editing, the Return key advances the text pointer to the next line In the field; the Enter key closes the field by removing the text pointer from whatever field it Is In; and the Tab key advances the text pointer to the next field on the card. Therefore, these keys won't affect HyperTalk scripts from their text field activities. How you decide to trap retumKey, enterKey, and tabKey messages will vary markedly from one stack to another. One potentially helpful application Is to avoid possible confusion between the Find and Message capabilities of the Message Box. If you instead create a stack button that prompts the user (Inside a separate dialog box) for a search string, you can create scripts that let the user continue searching for that string by pressing the Return key. Just as if the search string were in a Find Box. Being able to trap for these three keys will prove a flexible feature when you start developing your own stacks. ARROWKEY ■ ......... .. ... .:„..•>, Each time you press one of the arrow keys on the keyboard , HyperCard sends an arrowKey message plus the name of the key as a parameter, as in arrowKey left or arrowKey down. The advantage to trapping for these keyboard actions is that you can intercept or modify these actions when you don't want the standard actions to apply (see chapter 2 for details on standard arrow key actions) , A good example is in a multiple-background stack. If you wish to keep the browser in a single background while he presses the left and right arrow keys, you would include a message handler in the background or stack that traps for the arrowKey message. If the parameter sent along with the message is "left," then have the script go to the next card only in the current background. That means that when the browser is at the first card of the background and presses the left arrow key, the script wraps the progression through cards around to the last card of the background. You would include a similar trap for the "right" parameter. 390 HyperCard's Programming Em^ironment DOMENU HyperCard gives its programmers complete control over the way browser accomplishes tasks through menus. Each Ume a menu command or its Command-key equivalent is invoked, HyperCard sends a doMenu message, with the menu item as a parameter, as indoMem : Find. . . or doMenu Home. The parameter is spelled exactly as it appears in the menu, complete with three dots (an ellipsis) If they're in the menu, By trapping for menu commands, you can do things like disable i specific menu items for the sake of information or stack protection. Or you may wish to enhance certain menu commands . like flip to a "good- bye" card when the user chooses Home from the Go menu. If you recall the arrowKey trap to keep browsers in the same background, you would do the same kind of trapping for the Next and Previous menu items in the Go menu. You must be aware, however, that when you trap for doMenu, even ^ ; menu selection gets trapped at the same time, even though you want ■ ' ! to trap for only one or two items. To let other menu selections work their way up to HyperCard for execution, you'll have to pass the messagf along the hierarchy. Here's a typical script that traps for the Home menu command. , . ..^^ ; ■ -.t^ ;Hi:< '^h : : ■■ ; . ,. on doMenu item -r ^ d ' i: : If item is "Home" . V :r then put "Thanks for browsing" into Message Box pass doMenu ^ end doMenu We'll be covering the If-then-else and pass constructions later, but Hiis should keep you out of trouble if you rush to experiment now. ' By the way, if you discover that you entered a doMenu messase • • handler into a card or background script without the pass command, you won't be able to open the Script Editor for that object. To gel out of this Jam, type one of the following command hues into the Message Box (even if you have to type blhidly into a hidden Message Box), set script of this card to empty or * ■ ' set script of this background to empty . , ' ' ' Unfortunately, if there were other message handlers hi the object' script, they'll be erased with these commands. Therefore, experim J, with doMenu in object scripts that have no other message handlers . 1 them. Messages, Hierarchy , and Inheritance 391 IDLE Several times we have demonstrated that HyperCard sends the idle message when nothing apparently seems to be going on In a stack. Interestingly, when HyperCard sends a mouseWithln message, it alternates between the mouseWlthin and Idle messages. Tills occurs so quickly that It may appear as though HyperCard Is sending both messages simultaneously. Let's examine this In slow motion so you can witness what's going on behind the scenes. To demonstrate this, you'll be putting an Idle message handler In a card script and a mouseWlthin handler In a button script. Each handler will perform a different arithmetic operation on a value in the Message Box. The idle handler will increment the value by 10; the mouseWithln handler will Increment the value by 1 . Before you begin, make sure the Message Box is either empty or has a zero In It. 1. If you still have one of the sample buttons from an earlier experiment, open Its script dialog box. If not, create a new button and click on the Script button In the Button Info dialog box. 2. If the button has other scripts In It, delete them all so that nothing will Interfere with your experiment. 3. Type the following script into the button's script dialog box: on mouseWithln add 1 to message ■ : ■ :f^}U':i> . . wait 20 ' end mouseWlthin and click the OK button. ■ - ?v 4. Hold down the Shift key and choose Card Info... from the Objects menu to reach the card's script dialog box. 5. Make sure there is no other "on idle" message handler in the script. If there is, delete It. ^ ■■.^■r-i^ ^~.u 6. Carefully type the following script into the card's script dialog box: on idle ' add 10 to message wait 20 ^ , . . , ,1 . • , end idle and click the OK button. 392 HyperCard's Programming Environment The addition of the "wait 20" commands will slow things down enough so you can see how the Idle and mouseWithin messages work with each other. When you close the card's script dialog box, the value in the Message Box should be slowly incrementing by 10. Move the Brovjse _ .. tool into the button containing the mouseWithin script you just entered and watch what happens in the Message Box. The value Increments by 10, then 1, then 10, and then 1 again. The instant you remove the Browse tool from the button, the increment returns totheidle's lOonly, If you press the mouse button, HyperCard stops sending the idle or mouseWithin messages, because it is busy sending the mouseDown and mouseStillDown messages to whatever object the Browse tool is ,., ^ atop at the moment, whether it be the card or button. , Idle handlers can be useful for effects such as displaying an elapsed timer on a card, in which the current time is continually being placed into a text field. The Home card has Just such a message handler in its • script. STARTUP, SUSPEND. RESUME, AND QUIT , . . Four system messages let you trap for your movement into and out of HyperCard. HjrperCard sends a startup message to the first card of the stack that HyperCard opens at the beginni; ig of a session. If you double- click on the HyperCard icon from the Macintosh desktop, HyperCard will automatically start up with the Home stack. But you can also start with a different stack if you double-click on the icon of a HyperCard stack on the Desktop. In that case, HyperCard sends the startup message to the first card of that stack. Startup message handlers, however, are more often placed in the stack script, since it is more natural to think about the stack starting up than the card. The quit message functions similarly to the startup message, except HyperCard sends it when it receives the Quit command from the File menu (or a press of Command- Q or a script message that performs the Quit operation) . A good application of the quit message would be to trap | for it and display a good-bye card directed at the user. i Both the suspend and resume messages revolve around HyperCard's ' ability to run (launch, or open) other Macintosh applications from within HyperCard. When you open another application, HyperCard k sends the suspend message. When you quit the external application, * you automatically come back to HyperCard at the exact spot from which you launched. HyperCard sends the resume message, meanins you are resuming your HyperCard session. It's important to recognize that a resume message is entirely different from a startup message. Therefore, if your Home stack script features special instructions upon start-up, such as showing the Message Box Messc^es, Hierarchy, and Inheritance 393 at a particular location, then the same instructions should be in the resume script so that the same settings will be in effect when you come back from running an external application. If you inspect the Hyper- Card Home Stack script, you'll see that HjperCard goes through identical setup procedures [In a long message handler called getHomelnfo) both on startup and resume. That concludes the list of HyperCard system messages and their workings within the hierarchy. There aren't that many, yet they carry the bulk of what your stacks will be working with. You'll also be able to create your own HyperTalk messages and message handlers, which we'll get to In a later chapter. Where to Place Message Handlers Since HyperCard system messages can go in so many different levels of the hierarchy, you may be concerned about choosing the '•correct" location for various message handlers. Of course, handlers for field- or button-specific functions belong in those objects. But you may often be faced with the choice of putting a message handler In the stack or background object. Moreover, as a stack design evolves, you want to know that your script work won't be In vain. As a general rule, place your scripts as low In the hierarchy as you deem feasible. For Instance, a newCard message handler Is best placed in the background rather than In the card, even if your stack design seems to call for only one background. By placing the script in the background, you leave yourself open to adding new functionality to the stack in the form of another background design for a second group of cards (perhaps a help section) with its own newCard message handler. Later, when you learn to make your own HyperTalk messages and message handlers, you'll begin to load up your Home stack with all kinds of useful scripts that simplify your stack creation or navigation around your HyperCard world. The reason these handlers will go into your Home stack Is because you'll want access to them from any stack or card you use. When the handler is in the Home stack, you know for certain that the message will find its handler. If the handler is in a different stack, you'll have access to it only from within that stack. A stack with a single background would place most of its handlers in the background. A stack with only one card would have most of its handlers in the card, Including handlers like openStack and closeStack. The bottom line, then. Is to think through the intended scope of each message handler before assigning it to an object's script. Do your best to visualize all the possibilities of where you'll be In your HyperCard 394 HyperCard's Prpgraxnming Environment aff 1 . world when you want that handler to come to life. Start visualizing with ?jf ?• the handler in the Home stack. Then try it one level lower, in the stack obj ect, and see if it "works" there. Keep Inching down the hierarchy until you find that the handler will no longer be accessible from every possible circumstance. Then place the handler in the object one rung above that. Study the card, background, and stack scripts in the Tb->(ij HyperCard Home Stack to see how handlers are assigned to various r.ir- hierarchy levels. External Resources One of the exciting design features of HyperCard is that it is open-ended to the extent that experienced Macintosh programmers can literally write their own extensions to HjrperCard's powers. If HjrperCard doesn't contain a command or feature that you want, you can add It In Pascal, C, or assembly languge, provided you have the know-how for such explorations. The additional programming you'd add would be turned into a chunk of computer code called a resource. Resources can be added to a HyperCard stack using a resource mover utility program. The resource code bears the name of a command you would put in a HyperTalk script or type into the Message Box. When HjrperCard sends the message with that command in it, the message works its way up the hierarchy. When it reaches the stack level, the message first seeks a match In the stack script. If there is no match there, it looks for a match In an external resource, if one is attached to the file. It follows the same procedure at the Home Stack level, as well. If there is still no match, then HyperCard shows the alert box that it can't understand that command. Many third-party HyperCard developers are taking advantage of this resource extensibility of HyperCard to build in many features you cant get from HjrperCard alone. You will find these HyperCard resources cir- culating among user groups and electronic bulletin boards. They may even intrigue you enough to pursue learning one of the development languages for the Macintosh so that you can write your own resources. This feature makes HyperCard the kind of software "engine" you cant really outgrow. 01 Jr, Messages, Hierarchy, and Inheritance 395 Inheritance In all our discussions about the HyperCard hierarchy and the passing of messages, we've been taking the perspective of the message- watching the message start at one object level and claw its way up the ladder. More traditional approaches to the object orientation of the HypeiTalk language might look at this hierarchical system from the opposite direction, that is, how objects lower in the hierarchy bear resemblances to certain properties of objects higher up the ladder. Let's take as an example the relationship between two HyperCard objects, the stack and the background. If we start off with a stack, we know its properties. From there we can deflne an object, called a background, which has some of the properties of a stack (its ability to pass messages, for instance) but also some unique properties of its own, such as its graphics layer. In a more formal object-oriented language, we'd say that the background inherits the properties of the stack and then adds some properties of its own. A favorite way for writers to explain inheritance is to use some profession, like accountants or physicians, as a metaphor. For ex- ample, all doctors have a basic core of medical training, which they pick up during their medical school years. As each doctor progresses through schooling and residency, he or she picks up a specialty. Despite the specialty, the doctor inherits all the basic medical knowl- edge by virtue of going through medical school. Now, this Is grossly oversimplified, compared to the structure of a full object-oriented language, like SmallTalk or MacApp {an object-oriented Pascal language available to professional Macintosh programmer). But the point is that these languages start with a core of objects from which the programmer creates derivative objects (descendants, as It were), which inherit some or all properties of their ancestors and add some of their own, HyperCard, on the other hand, has already prede- fined the derivative objects from the HyperCard "object." Those are the now-familiar Home, stack, background, card, field, and button. Since these objects are already defined, we can take a simpler view of how the HyperTalk object-oriented system works. We can watch a message be sent to one object and passed up the hierarchy until it finds a match (or disappears without a match). This viewpoint Is so much easier to visualize that we can leave further discussions of inheritance to the textbooks. . , . ., CHAPTER 20 Introduction to' H5^eiTalk Commands The bulk of the messages you write in your HyperTalk scripts start with HypeiTalk commands- those operations, like Go, built into Hyper- Card. In most cases, your scripts elsewhere in the stack won't trap for these command words, because you'll want HyperCard to carry them out unaltered. HyperTalk command words comprise a large portion of the vocabu- lary of the HyperTalk language. The commands also make your stacks come to life, performing tasks that affect the information stored in cards and that affect how you or another browser interacts with the stack application. It is therefore essential that you understand the meaning of each word in the command and function vocabulary (functions are covered in chapters 28-32). You may not use every command word in your stacks, but the more you know about the capabilities of the language, the easier it becomes to dream of HyperCard applications. In fact, chances are that many of the capabilities of HyperTalk commands and functions will give you ideas for stacks and information manage- ment tasks you'd like your Macintosh to perform for you. In the next seven chapters, we'll examine each command word, explaining what it does, how it might be used in a stack, and anything you should watch out for when using it. Each command's explanation will be a stand-alone section, so you can use this part of the book later as a reference guide to a particular command you wish to place in a stack of your own design. To make it easier to learn the commands and find them later, we've divided the words into groups of related com- mands, within each group, from the simple to the complex.. 397 398 HyperCard's ProgranunUy Environment Before we jump Into the commands, however, we must explain conventions we use to list the parameters of each command. Notation Conventions Virtually every HjrpeiTialk command requires additional words follow- ing it. Usually, the words, known as parameters, describe what the command should be working on. For example, in the command "Go next card," the words "next card" define where HyperCard should 'go' as the result of the command. Depending on the nature of the command, parameters may be text, numbers, or a combination of the two. Moreover, some commands have more than one parameter. COMMAND PARAMETERS To designate a parameter in the following listings, well use the same notation convention you'll find in the HyperCard on-Une help system. All parameters are enclosed inside less than and greater than symbols (< and >) . Please note: This notation Is for the convenience of the listings only; none of the enclosing sjrmbols or brackets actually appears in ' J HypeiTalk script. The word used to describe the parameter tries to detail the nature ' " ■ ' the parameter that HyperCard expects to find after each command. F example, the "next card" parameter is called a destination, since specifies a location to which HyperCard should "go." Therefore, ; ■ command notation would be -yU !?t'-.. y '^ H - i /^'ietwu ^ go j < . V ' - This means that any valid destination may be substituted for "neJrt ' • card" ui a Go command (we'll see what constitutes a valid destinatl in a moment). ' ■ Some commands also have parameters that you don't always need, • ' depending on the circumstances. If you don't fill in this parameter, ' ' HyperCard usually assumes some default or previous setthig. F (tempo l ^ Notice that there is a word Inside the square brackets but outsidetk optional p£uumeter's symbols, the word "tempo." What this means Is Introduction to HypetTalk Commands 399 that if you specify the tempo parameter, you must also precede it with the word "tempo." Hierefore, an actual two- parameter command line In a script would look like . -s .. play "Harpsichord" tempo 120 "c d e f g a b c" ' You'll see apparently free-standing words in the command notations quite often, as In multiply by which mean that you must have two parameters {neither one is optional, since there are no square brackets), and they must be separated by the word "by." OPTIONAL COMMAND WORDS HyperTalk tries to emulate the English language as much as possible so that newcomers to programming will feel comfortable Issuing commands they recognize. At the same time, a more experienced HyperTalk user may prefer to issue commands tn shorter forms. To accommodate the newcomer, HyperTalk accepts additional words tn several commands that make it easier to understand the meaning of the command. The Go command is a good example. A more natural-sounding Go command would be "go to." as in "Go to card ID 300." HypeiTalk will accept either form, although it considers the "to" as optional. The notation that shows you which command words are optional are square brackets. Therefore, the notation of the Go command now reads go [to] You can use the "to" if you wish, but it is not mandatory. Several HyperTalk commands accept more than one word as parame- ters or parameter separators. For example, the Put command lets you put a source before, into, or after a destination. HyperTalk accepts any one of the three prepositions as a valid parameter separator. In the foUowlng chapters' listings, the command notation that shows your choice of alternatives Is a vertical bar between the choices, as in before I into I after resulting in a final notation of put before I into I after for the Put command. In all the command explanations in the following chapters, we'll provide several examples of what real command lines look like, so don't be too frightened by the apparent complexity of this notation. With a little practice. It will become second nature to you. 400 HyperCard's Progmmmtng Environment Containers ' " - - -^ Many HypeiTalk commands perform operations on mfomiation. But for this to occur, the information must be located someplace that a script can access by name or number. These places are called contain- vfi' ers, and they take many forms in HyperCard. Among the most recognizable containers are text fields and variables. Now add to that list the special It variable, the Message Box, and any text selected in a field, which automatically becomes a container called "selection." All these containers hold information that can change as • - the result of a HyperTalk command acting on that container. All containers store the information in text form, even when the text is all numbers. If the HyperTalk command expects a number in the containers it deals with, HyperCard will internally turn the text numbers into values for the command to work on. Even if some 'j ' arithmetic is performed on the value of numbers in a container and a new number is placed back in the container, it goes back into the i container in the same text form. This eliminates the nasty prerequisite i > ' • -■ in most information storage programs (databases) of predefming a field as either a numeric or text field . In HyperCard , the same container may ■ ' be called upon to hold what seems to be a numeric value at one time, and a text string at another, or a date at yet another time. * ' ' A comforting feature about containers is that whatever you can do to ■ Information in one kind of container, say a field , you can do to any other • r-.fT^ . itind Qf container, say It. You can treat all containers the same, as far | ■- as manipulating their information is concerned. But you must respect ? their distinctive properties. -V i FIELDS - - > ■ ' ' ■ All fields hold information for a single card, whether the field is In the [ ' " ^ background or card layer. Therefore, when you refer to a field in a ! HyperTalk script, you will usually refer to the field by its domain ■' (background or card), by the field name or number, and by the name or number of the card in which the field is located (unless it Is the current card). The form would be "card field ID 203 of card 'Jane'" In a script. If you don't specify a domain for a field, HyperCard assumes that you mean a background field. But if the field you're referring to Is a card field, you must specify the card domain as part of its notation. One special property of fields that no other containers have is that a field retains its contents even if you quit HyperCard. The information stored in a field is written to the disk before you close a card. IntroductUyn to HyperTaik Commands 401 Information stored In all other containers is volatile, meaning that it disappears at various times, as noted below. LOCAL VARIABLES , r*r .T ir; ; . ^ . bf- ' You may recall our discussion about local variables in chapter 18. A local variable is assigned a name when you place information into it. From there, you can perform any HyperTallt operation on the informa- tion that you would with any other container, provided you perform the operation within the same handler that created the variable in the first place. A simple script involving a variable would look Hke this: on mouseUp \j-:-h>t > put 10 into hat — creates a variable named "hat" and -- stores 10 into it add 20 to hat adds 20 to the value stored in "hat" put hat into Message — places a duplicate of the -- contents of "hat" (which is now 30) -- into the Message Box < end mouseup The instant that this script ends, the variable "hat" is no longer remembered, nor is its content. Therefore, you use local variables as temporary holding places while a handler is running. You don't really see variables, like you do fields and the Message Box. When you store information in a variable, you have to trust that HyperCard wiU keep the information intact (it does). You can store as much information in a variable as you can In a field, including multiple lines of text. ^ -><*'' ■ .-^jij, . ; -.'•'». !<:.•>■; ■.nri >>}. ,■■,!!■■.;>'! The special local variable. It, Is not remembered after the end of the handler it is used in. As you'll learn shortly. It is the recipient of much Information available about objects. For example, you can issue a HypeiTalk command that gets the screen coordinates of a particular button. HyperCard places that information into It, where you can retrieve the data and do whatever you planned for that information. You also have complete access to It, Just as with any variable, but you should be aware when HyperTalk's other commands might overwrite whatever is in that variable. For that reason, use the It variable only when you know for certain that no other HyperTalk operation will change its contents between the time you store something there and need to retrieve it. 402 HyperCard's Programming Environment A GLOBAL VARIABLES - ' ! As a container, a global variable Is Identical to a local variable, with one exception. The content of a global variable is not forgotten when a i handler using it ends. Therefore, you can use a global variable to hold ' Information between scripts, even if the scripts are in objects of ; different stacks. HyperCard keeps global variables alive, independent : of the stacks you open and close. Once you quit HyperCard, however, ' 1' the global variable and its content are erased. ■ ' ; Creating a global variable is a slightly different process than creating a local variable. In chapter 24. you'll meet a HyperTalk command diat both gives a global variable life and lets HyperCard know that you're going to use a previously created global variable in a script. THE MESSAGE BOX Perhaps the most "physical" container In HyperCard is the Message ] Box. Designed as a window, you can drag it around the screen, taking its contents wherever it goes. The Message Box differs from other containers in one important] r , ; ■ * respect. It holds only one line of text. Even if you try to put a multiple- en " it lined chunk of text into the Message Box, only the first line is stored there. .y- ' ; . The content of the Message Box is erased when you quit HyperCard. SELECTION Whenever you click and drag across text in a card or background field, that selected text becomes a container called Selection- like a con- tainer (selection) in a container (field). Scripts may then treat its contents like any container. Including putting it Into another container, ' performing arithmetic with it, or even replacing it with the contents of a different container, u. " Programming scripts to work with selection is more convenient for the . . ^"-i user than making him Command-drag over text to pick it up before iTo '■■ ' f searching or dialing. #5 Container Components Since a container may hold many words and lines of text, your scripts need a way of accessing individual pieces of that text. For example, If • ' a three-line field in a card has three telephone numbers in it, you may Introduction to HypeiTaVk Conunands 403 FTEMS wish a button script to dial only the number In the first line. The script needs to extract the first line from the entire field. Information In a container consists of four different components: items, characters, words, and Unes. An item is any string of text between commas. For example, if a field named "FViend" has "Joe Jones, 1212 Main Street, Brookljm, Iowa, 50040" in it, there are five separate items in that container. If you then want a script to put only some items into another card, you could single out the name as item 1 of field "Friend" HyperCard interprets this line as meaning "Joe Jones" In this case, without the following comma. In fact you can try this using the Message Box and the Address stack supplied with HyperCard. Open that stack and create a new card, which you'll use as a testing ground. Next, type some Information into the first field of the card (where the name and address usually go), complete with commas between several words. Into the Message Box now type j,,.^ ; item 1 of field 1 HyperCard Immediately interprets and replaces your phrase with the content of the first item in that field. Try the phrase again with different item numbers. Notice that when you specify an item as a component in some operation, the comma is not carried along with the Information. You get the pure information without the comma separators. CHARACTERS, WORDS, AND LINES >£; ^ i n HyperCard also gives you access to individual characters, words, and Unes of a container. Starting from the beginning of the text string in the field, count the number of the character, word, or line you wish to extract or change. Then refer to the component by its name, character (or cha/j, word, or line, plus the number. You may also refer to a range of components by name and number, as In ujord J to 5 ojjield 'Address. "By extracting a range of components at one time, you will speed numerous text manipulation tasks in HyperTalk. In its attempt to be more English-like, HyperTalk pro\'ldes an alternative way to refer to the first ten, the last, the middle, and random components in a container. Instead of referring to u;ord J in a script, for 404 HyperCard's Programming Environment example, you can also write first word. HyperTalk provides the following ordinal numbers and references: first eighth second ninth third tenth fourth last fifth any sixth mid seventh middle The "any" reference will give you a random component of the container, as In any word of field ID 109, while "mid" and "middle" give you the middle component, even of a multiple line field. CONCATENATING COMPONENTS As you begin extracting components from containers in your scripts, - • you will occasionally find it necessary to Join components together In a second container. For example, if you wish a newCard script to place the current hour in a new card's Time field, you could call upon HyperCard's the time function, which returns the 12-hour time in a form like 4; 10 pm. But since you don't want the minutes to appear in the Time field, then you'll need to build the contents of that field from components. You would want to join the hour and thCAM/pM designa- ' ■ " tion together. Joining text like this is called concatenating (kon-kat-en- a-ting) text. " ■ In HjrperTalk, the mechanism that concatenates two pieces of text is ' " ' the ampersand symbol: &. When this symbol appears between two pieces of text, the pieces are Immediately considered one piece. Watcli how this works, using the Message Box and the Address stack you used a moment ago. : ; r . 1 , Clear the text in the new card you Just created. ' -' <• 2. Type the word "hello" into the first line of the name field, , . ,^ 3. Now type the following statement into the Message Box: char 5 of field 1 & char 1 of field 1 Granted it's a long way to go to get HyperCard to say "oh" in the Message Box, but this exercise demonstrates how the ampersand works to concatenate text. Notice, however, that there are no spaces between the components joined by the ampersand. That's fine when you're joining characters into a word, but you vrfll need spaces when Joining words together. To Introduction to HypefTalk Commands 405 add a space while concatenating components, type two ampersands together, as In word 1 of field "Names" && word 3 of field "Names" If you need even more spaces, you can place strings of spaces amid the components being joined, such as word 1 of field ID 908 & " " & word 5 of field ID 908 COMPONENTS OF COMPONENTS- CHUNKS So far, we've been looking at how you refer to single components Inside a container. But you can also specify a component in relation to other components inside that container. If the first line of a field contains two four- letter words separated by a space, you could refer to the beginning letter of the second word as being either the sixth character (four characters of the first word plus one space character) or the first character of the second word (char 1 of word 2), You can freely "nest" these component expressions— chunfc expres- sions, they're called— as you see fit. You specify churik expressions from the narrowest to the broadest chunks, as in "char 2 of word 3 of item 1 ofline 6 of field 10." We can now move onto the actual commands in the HypeiTalk language. We'll cover them in logical families to help you better learn the commands in context. CHAPTER 21 Navigation Commands Among the most common HyperTalk commands you'll use in your scrifib are navigation commands- those that take the user from one card or stack to another. Also in this group Is the Find command, which lets you add much perceived power to button scripts, since a click of such a button will not only go to another card or stack but will locate desired information for the user. All the other commands In this group affect the way the user wends his way through your stacks and HyperCard In general. [to] Purpose: Takes the browser from one card to another card, or from one stack to another stack. / .^ i.^ - When to Use It: A simple shift from one stack to the first card of another stack uses this command, specifying only the name of the stack as a parameter. You can be more specific in your motion to another stack by specifying a particular card In the second stack. If you like, nils command also links any two cards together, whether they be in the same stack or different stacks. While a browser has menu commands and arrow keys avaCable for moving to the next and previous cards, many stacks also have left- and right-facing arrow buttons that perform the same functions as the menu commands- going to the previous and next cards. Any button 407 408 HyperCard's Programmmg Environment I'r that links two cards must employ the Go command to make that link happen. In fact, H3rperCard itself generates Go commands when you use the Link To . . . option in the Button Info dialog box. The vast majority \ of button scripts will contain a Go command. ' Parameters: The parameter accepts all possible ways of referring to a card and/or stack in HypeiTalk. If the desUnation Is a specific card, the parameter must contain the word "card" somewhere (with exceptions noted below). If you refer to a card by its name, number, or id number, the form for the parameter would be card "Index 1" card 24 card ID 4A58 All of these identifying names and numbers tacked onto the "card" can also be inside containers, like fields or variables. Fori example, if the text "Index 1 " were In a variable named 'Tom," you could | Issue the Go command in the following manner: go card Tom Another card destination type is any ordinal number, opdor followed by the word "card," as In go third card go any card - goes to a random card in the stack go last — the word "card" is optional with an ordinal Additional card destinations you can use with or without the word j "card" are found in the HyperCard Go menu: Back Recent Previous (and Prev) Next Home If the destination Is in another stack, the stack name must be part of the destination parameter, and the stack name should be enclosed fn quotes (although it's not mandatory). The word "stack" is optional. For : HyperCard to find the stack by itself, the stack must be in a path listed in the Stacks card in the Home Stack. Otherwise, the standard file dialog box will ask you to find the stack file and open it. Optionally, you can spell out the stack's entire file path as part of the stack designator parameter to the Go command. When you specify a stack name as a destination, HyperCard opens the stack and leaves you at the first card of the stack. '1' .U'joJ- Navigation Commands 409 Examples: go to card "Index 2" - a card named "Index 2" in current stack go "Address" — go to first card of a stack named "Address" go to card ID 431 of stack "Invoices" go to card "summary" of Invoices go to background 2 the fifth card of the current stack go any card of stack "Dice" -- a gambler s random call You Try It: From the Home stack, type Command-M to show the Message Box and type in the following series of Go commands. If the Message Box disappears along the way, bring it back into view with Command-M. Watch what happens after you press Return with each command. . ; ' go "Datebook" - go next go to card ID 51275 of stack "Help" go back put "Datebook" Into variable '•■ u.-'H);- ■/.■.. go second card of variable ■■ ».•<■..■ ''''.j ' go home ■ a -. i .• • - ' • ' , , ' ; ■ ' ■ ' > iT; find [char|acter]s I word] [in l ! ; Purpose: Searches the current stack (or Just one field in the current stack) for the occurrence of a text string. When to Use It: Use the Find command to search for the occurrence of text in a stack. This is the same Find command that appears in the Message Box when you choose Find from the Go menu. When a script issues the Find command, HyperCard remembers the text the script is searching for. If you then choose Find from the Go menu (or type Command-F), the search text will already be Inserted In the Find strlnjg. A Find command is not like the Message Box type of search In one respect. When the Find command performs the first search and comes up with a match other than the one you wanted (for example, a different "John" in your name card file), you can't simply press the Return key right away to keep searching for other occurrences of the text string. Pressing Return becomes a natural reaction to browsing through a stack, to be sure. If you wish to continue browsing for the string In the scripted Find command, choose Find from the Go menu and then press Return (or Enter), You won't have to retype the find string, because HyperCard automatically Inserts the last text it was asked to find. HyperCard's Progranuning Environment If your overall goal is to find text in a card from a different stack, then make it a two-step process. In the first step, use the Go command to get to the desired stack. In the second step, use the Find command. Parameters: You can instruct HyperCard to search for a match of the text either as a whole word or just as characters within a word. When you don't specify one or the other (as happens in the Message Box), HyperCard assumes you want to search for whole words only. This is the most likely type of search you'll want your stacks to perform. But If you wish to search for characters Instde words (like "our" inside "source"), then specify either chars or characters after the command. The parameter is a common parameter type, standing for any kind of container, like the contents of a field or variable. Therefore, you can type in a specific text string for the Find command to look for if you wish, like find "Harry" but string-specific searches are usually more appropriate for Message Box searches, in which you type the text to search. In scripts, you will more often use a container as the source of search text. There will also be times when It is appropriate to search for the results of a function, particularly date and time functions. For example. If you have a daily appointment book that has each day's date listed in a field in the format returned by the date function, you can use that function as the source of the search string, as In ■ ; ■■-'!- •■><-t^. flndthedatc -^i - t.- But since searches are done on the text makeup of the date function, the format of the dates in the card fields must be identical to that of the function used to search for the card (see chapter 30 on time and date functions). It is sometimes helpful to narrow the search to a single background field with the parameter. Two benefits shine brightly for narrow- ing the search. The first is that the Find command will not stop on a match in a field you're not interested in. Second, the searchtng will take less time, because HyperCard will find fewer possible matches when It performs its searching wonders. A field parameter, which must be separated from the source parame- ter by "in," requires the word "field" and some identifier to single oui which field you wish. The three ways of identifying a field- name, number, and lu number— apply here, so you can say, find "Harry" in field "Name" You may also use ordinal field numbers if you prefer, such as find "Harry " in second field ;;r' v^rv Navigation. Commands 411 Examples: find field 1 In field 2 find variable 1 -- concatenate text into a variable to find ^ find "3 12-" in field "Area Codes " You Try It: Go to the Address stack, show the Message Box, and type in the following commands. After tjrplng each command, press the Return key a few times to see how many matches HyperCard finds. find chars "a" ^'^'^ * ' find word "a" find "Ron" in field 1 - noi?; :v.^t;r- ^ . • find chars "Ron" in field 1 'i ' ' « ^ - find "John" in field 2 -eii' ; ; ; - ! .n > ^ : find "555" infield 2 ■ ' ' ■ ■ find chars "22" > '^'4 vi ■ ■ - ^ : .d: ■ . i find chars "22" in field 2 ^' " h-' '' ■ ' = ' push I this I recent 1 card pop card [ into ] Purpose: Push temporarily marks a card for Instant retrieval with the Pop command. When to Use It: We can use the old library card catalog metaphor to explain the concept of pushing a card. Imagine that you've found a card to which you want to refer after checking out some other cards. In the library, you might place a slip of yellow paper or other flag that will be easy to find, even if you wander off into other card drawers. When you wish to see that card again, you look for that flag. In HyperCard, pushing a card is the same as tagging the one card. When you push a card, you can then wander about any HyperCard stacks and cards as you please. To see that marked card, you simply issue the command Pop card. HyperCard presents the marked card before your eyes. Pushing a card frequently makes sense when you are constructing elaborate H3rperCard environments for yourself or others, particularly those that branch all over the place. By pushing a card before branching and then offering a button with a script to pop the card, you help the user navigate through the environment, by providing a consistent and convenient method of Instantaneously returning to some landmark. The instant you pop the card, HyperCard removes the marker. 412 HyperCard's Programming Environment This push and pop terminology didn't originate from a library envi- ronment but from a programming concept commonly modeled after a spring-loaded stack of cafeteria trays. When you push a tray onto an existing stack of trays, the one you most recently pushed will be the first one to be pulled off— popped— by the next person In line. As you pop a _ card, HyperCard displays that card and removes it from the internal r*-- ,. pile. It Is critical to remember that pushed cards operate in a last-in, flrst-out environment. Unless your scripts exert unusual control over the browser's navigation through a stack, it's best to push cards no deeper than the topmost level. Another design consideration is whether the burden of pushing a card belongs to a card prior to linking or to a card after linking. TWs decision depends on the stack and link structure. If your links are set up so that the only way to get to card B is Erom card A, then you can safely place a Push card command in card As button script that links the two cards. But if the stack is such that several cards link to card B, it will be more efficient to place the command push recent card into the openCard script of card B. Then, no matter what card you were viewing prior to reaching card B, that card will be pushed onto the pile, ready for popping when you're done with card B. Parahetgrs: The Push command requires a parameter only If the card to be pushed was the card prior to the current card. If so, then specify ■ the recent parameter. If you don't specify which card to push, Hyper- ^ ' C^d assumes you mean the current ("this") card. The Pop command has an optional parameter that lets you pop a card without actually going to that card . You can pop a card into a container. Two things happen when you do this. First, the card comes off the pile without showing it on the screen. Second, the popped card's id and stack location go into the container you specified. ^ ' 2' Let's say you push two cards onto the pile and want to go back to them ' '•• not in the reverse order (which plain Pop card would do), but in their original order. One way to handle this would be to pop the top card into ' a global variable, pop the next card to actually go to it, and later go to the card whose id is stored in the global variable. \ ,ir' push card 4;; push recent card pop card pop card into it r 'h Ay- Navigation Commands 413 You Thy It: Since there isn't a lot to experiment with in the way of different forms for this command, let's tiy pushing and popping some. Type the foUowmg commands Into the Message Box from the Home card: go card 10 of "Address" push card go card 3 : pop card pop card —this taltes you baclt to the Home card go card 100 of "Help" , , , push card go next push card go first pop card into firstOut pop card go card flrstOut help Purpose; Brings the user to the HyperCard help system. When to Use It: It's unlUtely you'd use this command In a script unless you plan to trap for the help message to bring the user to a stack- specific help system of your own design. HyperCard help is available from the menu {in the Go menu) and a keyboard equivalent (Command- ?), so unless you turn off the menus in your application, you can leave access to the HyperCard help system to the menu. Parabieters: This command has no parameters. Example: - help You Try It: Even though the HyperCard help system is available via the menus, you can also access it at any time by typing help Into the Message Box, Try it now. CHAPTER 22 Action Commands The Action Command category contains some of the most powerful com- mands in the HypeiTalk language. The most important of these is the Put command, which you'll use constantly to move Information around among fields, variables, and other containers. Other commands let you do things such as making menu selections from a script, dialing the telephone, launching other Macintosh applications, sorting informa- tion stored in fields, and even controlling a videodisc player. Purpose: Moves new information into a container or moves information from one container into another container. When to Use It: You'll use the Put command more often than any other command in your HyperCard scripts. This is the command you use to retrieve information from fields for manipulation; it's also the command you use to shift the manipulated Information back into fields for display and permanent storage. In the interim, you'U be "putting" informaOon Into local and global variables, the Message Box. the selection, and It. Despite this command's simple syntax, it is capable of rather remarkable information manipulation ftself. It allows you not only to Insert information anywhere Inside a container (for example, between the second and third words of the fourth line) but also to replace one put [ Into I after I before ] 415 416 HyperCard's Programming Environment container component with new Information without having to disas- semble a container's content and reconstruct it. A typical application of the Put command would be to put the contents of a field into a local variable. Then other HypeiTalk commands either perform various operations with the variable or append additional information to the variable. Finally, the information from the variable is put into a iield In a different card. This Is but one of myriad ways to use the Put command in a script. Parameters: If you do not specify a container parameter, the Put command places the text of the source parameter into the Message Box, Both the source and container parameters can be containers. That includes any or all components of a container, like the "fifth word of the second line of field ID 40716." Additionally, the source parameter can be any text string or any arithmetic expression. Strings must, of course, be surrounded by quotation marks. Arithmetic expressions are those expressions that would resolve to a number if they were typed into the Message Box. When you put an all-numeric text string into a container, HyperCanI still stores the information as a text string. If, later, you perform an arithmetic operation on the container, HyperCard vrill try to resolve the contents as a number, so you don't have to worry about whether a digit is looked upon as text or a numeric value. While it is always stored as text, HyperCard wlil view it as text or number, as the situation warrants. Consequently, the following two commands accomplish the I same result: put 10 into field 2 .1- v:- •• X' (V put "10" Ulto field 2 Either way, you can later perform arithmetic on field 2, If you wish to add more than one word from one container to another container, you may do so with the help of ampersand (&) concatenation. For example, you could take the second and third words of two fields and place them into a variable called "box" with this command put word 2 of field 1 && word 3 of field 4 into box vrith the double ampersand assuring the Inclusion of a space character between the two words when they reach the variable, box. Your choice of preposition (into, before, after) turns out to be a powerful choice. Let's examine what happens with each one, The into choice can best be characterized as the preposition that signals the replacement of the destination container's content by the source's content. Therefore, If your command puts "hello" into a field, then no matter what was originally in that field (or any container), it mil Action Commands 417 be entirely overwritten by the new "hello." You can narrow the original text that is being replaced by the Put into command if you are more specific in naming the destination. An example will help demonstrate this. Say that field 1 contains the following text, To goof is human To replace the word "goof with the word "err," you'd issue the following command: put "err" into word 2 of field 1 This method of replacing text works with only one container compo- nent at a time, but one container component can be a range of components. For example, if the original text In field 1 was To goof up is human you could replace "goof up" with "err" by one command put "err" Into word 2 to 3 of field 1 In summary, then, use Put into to replace text in a container. Also be aware that you initialize a new local variable in a script by putting Information into it. In other words, if you say put "My name is Bill" into greeting " " you both create a new local variable, called "greeting," and put the text string into it in one step. Typing this line in the Message Box creates a global variable called "greeting". One other feature of the into preposition has to do with multiple-lined fields. If you wish to place an item into an empty line in a field several lines below the last item, you can simply specify the line number in the destination parameter, HyperCard will automatically place the requi- site number of return characters between the last entry and the line of the new information. With the before preposition, you can insert the parameter into an existing container without harming the container's original contents. If the destination container is specified as simply a field or variable, the new information is inserted at the very front of the text in that container. Therefore, still using our "to err Is human" field above, we can say put "Alex Pope says, '" before field 1 which results in field 1 reading Alex Pope says, 'to err is human Notice that we place all separating spaces and single quote mark in the text string we're adding to the field. By placing as much of this extra stuff into one text string, we obviate the need to go back and insert spaces, a process that slows the execution of the script. HyperCard's Programmmg Environment • ' You can use the "before" preposition and a more detailed destination specification to insert information before a character, word, line, or item in a container. For example, we can now say put ■', the writer, " before word 3 of field 1 to turn field 1 into J Alex Pope, the writer, says, 'to err is human making sure we add the required spaces to fill out the sentence. The after preposition works Just like the before preposition, except that it tacks information onto the destination container or component. If we say put ". to forgive Divine. " after field 1 the field will read Alex Pope, the writer, says, to err is human, to forgive ■ »>! . '.r Divine.' Similarly, you can put information after any component in a con- tainer, such as after the second character or the third item. An intriguingly powerful ability of the Put command is to post information to containers in cards other than the one you're looking at. The destination card must be in the same stack as the current card, but you don't have to go to it before putting the information there. The Put command, together with its three preposition possibilities and the degree of specificity offered by naming container components, provides you with enormous flexibility in retrieving and modifying text in any kind of HyperCard container. BXAMPLBs: ;i( put "Howdy, Jerry " into field "Greeting" put field 2 into temp -- temp is a local variable put word 3 of field 4 && word 6 of field 4 into temp put temp into temp 2 put word 1 of temp 2 into word 1 of field 3 put firstName & empty before field "'Last Name'" put empty & field "ZIP" after field ""State" put ""555-0700" into line 8 of field 3 put the time into field ""Time'' : r wrA- tar, . - You Try It: Putting Information into fields, variables, and other containers is a lot of fun to experiment with by way of the Message Box, Make a blank card in the Address stack so that you have two fields to play with. Then type the following commands Into the Message Box; Action Commands 419 put "Bill" into field 1 put "Atkinson" Into field 2 put "William" Into fiefd 1 , put "Bill " before field 2 put field 2 into field 1 put the long date Into field 2 — note the extra space put " 1966" into item 3 of field 2 ' put word 1 of field 1 into temp - a global variable ■ temp M'- '• put "Mr, " before temp ' temp put temp into word 1 of field 1 " ' ■ '' ■ ' >.'.c^'--if put item 3 of field 2 into temp2 ■ - ■•^J' add20totemp2 :>'^. put temp2 into item 3 of field 2 . n - By all means, continue playing with this great HyperTalk command. §Ct ; ,/ > Purpose; Places the contents or value of an expression Into It. When to Use It: This version of the Get command is a shortcut to the Put command when the destination container is It. In other words, get field 1 is identical to put field 1 into It Neither method is better than the other, except the Get command takes up fewer characters in the script, something good programmers try to achieve. ,,,,,,, , _ EXAMPLKS: / , You Try It: Use a blank card in the Address stack for this experiment. Type the following messages into the Message Box. put "text from field 1" into field 1 - : cr put empty into it 'c ' ■ ^'^ -'j getfieldl ■ • ■-■>■:■ it : ./ .^^ .w- • get the long time ,■- _ , : ■ get the long date get item 4 of field "Settings" 420 HyperCard's Programming Environment delete t ; «: ■ Pikposb: To remove text from a field of the current card or other container. When to Use: The Delete command Is not at all like the Cut menu command but more like the Clear menu command, which erases an item without putting it into the Clipboard. This command gives your script the power to pick single components of any container (charac- ters, words, items, lines) for deletion. Importantly, when you delete a line of a container, the entire text, plus its carriage return character, Is deleted with it. All text lines below the original line then move up one. Deleting words or characters does not take care of the carriage return. Remember that this command does not delete an object, Just text inside a container. Parameters: Any valid component name may be used as a parameter for the Delete command. The component must include the name of the container, such as a field or variable name. Examples: delete word 3 of field "Currency" K delete item 2 of it ■ delete line 5 of field 6 ; ; ^, ^. delete char 3 of word 4 of line 5 of field 1 You Try It: Go the the Address stack, create a blank card, and fill fields : 1 and 2 with text of your choosing. Then type the following messages into the Message Box: delete word 1 of field 1 . - if,;]^ , delete line 1 of field 1 :r^.f^^;y.:.\lS -T' get rect of field 1 .Jn'H-s/n it -- the rectangular coordinates of field 2 delete item 4 of it it delete item 3 of it it , . click at it delete ime 1 of field 2 i-!»;rf .. • ,. Action Commands 421 doMenu .n ^^iitj , Purpose: Chooses a menu Item while a script is rumiing. When to Use: Even If you turn off the menus for your application, you can build access to menu items into object scripts with the DoMenu command. This includes, incidentally, apple menu items if you wish to call up a desk accessory. For example, if you build some music into an application, you can include a setup card that reminds the user to adjust the volume on the Macintosh Control Panel and provide a screen button that brings up the Control Panel, in case the user doesn't remember how to get at it. It's hard to predict which menu items you'll call most often from your scripts, but our best guess would be the New Ceird and Delete Card items in the Edit menu. An incoming telephone logbook, for instance, might create a new card whenever the user opens that stack, since the main purpose of going to that stack is to make a new entry. The DoMenu command, then, would be part of the openStack message handler. Parameters: The DoMenu command must have a valid menu item as a parameter. The text of the menu item parameter must be exactly as the item appears in the menu. This means that if a menu item has an ellipsis (three dots) following it, the text of the parameter must also have the ellipsis. Spaces between words in the menu item must be preserved. And finally, the text must be either in quotation marks or come from a container (which stores text as valid text strings that all commands recognize) . There are some instances of DoMenu possibilities that would seem redundant. Most of the items on the Go menu can be Just as easily carried out by a regular Go command in a script. You'll have to watch out when specifying items in the Paint menu (which appears only when you are using a painting tool). Most items there require that a graphics area be selected first. If your script didn't previously select a region, HyperCard won't let you issue that menu command. That also goes for menu items that require selecting buttons or fields using their respective tools. Also watch out for the Cut, Copy, Paste, and Clear menu commands: The precise wording of these items cheinges depending on the material you're working with. For example, if you choose the Button tool and click on a button (either manually or within a script), the Cut, Copy, and Clear items all have the word "Button" appended to them, as in Copy 422 HyperCard's Programming Environment - * . Button. This word must be part of the DoMenu commemd parameters. Similarly, the Paste menu item changes to reflect the type of material in the Clipboard ready for pasting. It may be a Button, Field, Text, Picture, or Card. Examples: ^''^ ^ ^'''^'^ doMenu "New Card" , .. , doMenu "Print Stack..." - - doMenu "Print Card" ' ' You Tkv It: Although the power of the DoMenu command really makes sense only from within a script, you can still have fun with It from the Message Box, even if the operations you'll perform as experiments will be more efficiently carried out via the menus. Type the following commands Into the Message Box from any card in the Address stack, doMenu "Last" -- go to last card in stack doMenu "New Card" doMenu "First" -- go to first card doMenu "Background" - turn on Background editing mode i' doMenu "Background" - turn It off doMenu "Last" go to newest card ! doMenu "Delete Card" This should leave you with the same stack you started with before the experiment. .1 wait [for] ticks I seconds , until while u ii:. Purpose: Pauses execution of a script for a set time or until certain conditions are met. When to Use It: There are two times in particular when you'll need to e.rrr. summon the help of the Wait command that is tied to specific times. One is when a script carries out commands so fast that you need to slow . . i things down between some or all steps. The other is when you wish to • set up a self-running stack that flips through cards and stacks at a Off . predetermined pace that someone can read without using the mouse hf'j or touching the keyboard. /qu Delaying execution of fast-paced HyperTalk commands happens often during the creation and debugging of HyperTalk scripts. In chapter 19. for example, we were running a demonstration of how HyperCard mingles idle and mouseWlthin messages. In order to show Action Commands 423 you how the two messages worked with each other, we had each message perform some math and display the result in the Message Box. We had to slow the performance of these math problems with Walt commands. Even after you've debugged a HyperTalk script, if you find that users have problems with parts of the stack because certain operations take place too quickly for them to digest, you will probably have to insert some Walt commands to slow things down. Another application of the Wait command is during the opening seconds of a stack. If you wish to display a brief title card that acknowledges the stack's author and contains a copyright notice, you can set up an openStack message handler that shows that opening card for a specified period of time and then moves onto the functional part of the stack. The delay is carried out with the Walt command. So as not to stand in the way of an impatient user, that openStack message handler may also have a method of Intercepting the waiting by a click of the mouse button, thus shortening the delay. Waiting until or while certain conditions are met can be particularly useful if you want the execution of a message handler to be interrupted by the browser. For example, a handler might hold up at the Wait command if the mouse button Is held down (wait while the mouse is down). The instant the mouse button is released, the handler continues on. Parameters: Hie Wait command lets you specify the delay In one of two time units: ticks and seconds. Ticks are the number of Macintosh clock cycles passed along to the system. These come roughly sixty times a second, but the exact quantity varies with the Macintosh model you have and the amount of disk activity taking place during the running of the script containing the Wait command. Seconds are more accurate. At least you know there are always sixty seconds to a minute, regardless of how many ticks there may be. If you specify no time unit, however, HyperCard assumes you mean the much shorter ticks unit. To specify the quantity of seconds or ticks, you can type in a number or any arithmetic expression (that is, any container or text string that evaluates to a number) . Most of the time, however, your Wait command will contain a straight number, as in wait 1 0. If you are more comfortable writing Wait fora certain amount of time, feel free to do so. HyperCard ignores the /or, but it more closely resembles English. Parameters for the Wait Until and Walt While forms are Boolean (true or false) expressions. Generally speaking, these will be the result of mouse and keyboard functions that return true or false. See chapter 3 1 for further information about these kinds of functions. 424 HyperCard's Programming Environment Examples: ■■i'- ^-^ , .:^>v •., .' wait for 5 seconds svi ; . \,. wait 20 .:. wait 90 ticks wait for field "delay" seconds HKisidoiq jv ; !l * wait until the shiftKey is up ^ You Try It: It's pointless to type a Walt command into the Message Box. . J., . , unless it's merely for demonstration . Walt commands really belong only . J inside scripts. But we can show you how effectively the Wait command ^, . ; puts the Macintosh to sleep for the duration of the wait time. Go to the ; , . Address stack and place the Browse tool atop any one of the fields In , , such a way that the tool turns into the I-Beam cursor- but don't click ; , the mouse button. Now type the following message Into the Message ,.j Box wait 20 seconds Immediately move the cursor to the menubar. Notice that the cursor stays in the I-Beam, and you can't pull down a menu. When the twenh' ■ - • ' ■ seconds are up, the Macintosh wakes up from its nap, and the cursor changes to the familiar arrow in the menubar. ' * " Now try the same demonstration, but with the ticks unit. Notice how quickly control of the Macintosh returns to you when you use ticks m quantities under 100. Try other ticks and seconds quantities. I dial [with [modem] ] I ' ' • Purpose: Dials a telephone number through either a modem or an audio : device capable of sending Macintosh tones over the telephone line. . , When to Use: HyperCard's Address stack comes equipped with a script that allows your Macintosh to dial a telephone number typed into a card. If you develop stacks for yourself that Include phone numbers of ; ; :i . 'i any kind, you will want to have a button handy that wUl diaa a number ■ - : . ,. , directly from that card, rather than having to shift to another Hy^tJ- Card stack to do the dialing. ,,, There are many ways to implement the Dial command in a stack design. For instance, you can program the Dial command to dial a number that the browser picks up from a text field or selects in afield, ! ; ; , Or if a phone number is restricted to a particular field or line In a field, ^ i , the Dial command can point directly to that spot and dial the nurabei ( , ■ : without the user having to pick up the text. To utilize the intelligent dialing features built into HyperCard, yourf have to program the dialing script to first go to the Phone stack, whldi Action Commands 425 comes with HyperCard. This stack selects the dialing method best suited to your equipment situation (direct tone dialing from the Macintosh, tone dialing via modem, or pulse dialing via modem), and provides assistance in filtering out your local area code from listed phone numbers. The stack will also add dialing prefixes for local and long distance calls, if needed for your phone system. If you decide to skip the Phone stack in your dialing script, you have complete control over the dialing method, but you lose the "intelligence" of the stack. If you are dialing through a modem, you can issue as detailed a set of modem instructions as you desire. This, of course, depends on how well acquainted you are with modem commands detailed in your modem manual. Before a browser can utilize a script including a Dial command, he must have his Macintosh connected to the phone line either by way of a modem or the audio connector box offered by Borland International. Paraubtgrs: Every Dial command must have a telephone number as a parameter, even If you use the HyperCard Phone stack. Tlie phone number must be a text string enclosed by quotation marks, unless It is in a container (in which case, HyperCard sees the container's content as a text string anyway). If you t^e a Dial command into the Message Box or as part of a script using the actual telephone number in the script, the number must be between quotation marks. Otherwise. HyperCard will see the number as a subtraction arithmetic expression (for example, 555-3443 becomes 555 minus 3443). Therefore, always include the quotation marks, as In dial "555-3443" in either the Message Box or in a script. More often, however, your Dial commands in scripts wtll look to containers for the phone numbers, especially fields, variables, and the Message Box. If the user is instructed to "pick up" the text of a telephone number from a field, the phone number automatically goes into the Message Box. Your script, then, would say, dial Message Box to dial the number there. Similarly, you can instruct your user to select the phone number with the I-Beam cursor. This action places the text In a container called Selection, and the script would say: dial selection. Since the number is In a valid container. HyperCard considers it a valid text string for the Dial command. When you speciiy the Dial command with Just the phone number as the only parameter (in any stack other than the Phone stack), Hyper- Card generates the dialing tones for each digit internally. To have a modem dial the number for you, you need to add parameters about the 426 HyperCard's Programming Environment h modem. By saying dial with modem, you instruct - 1} i.; HyperCard to send the phone number and the following modem (,,,-; ^ /; parameters to the modem via the Macintosh serial port, rather than ; .!&; generate the tones internally. . Modem parameters vary with the type of modem you use, butthevast majority of modems connected to personal computers these days are compatible with a command language popularized by modems from Hayes-Microcomputer Products Company. Such modems are said to be "Hayes compatible," because they respond to the same software commands that Hayes brand modems do. A modem needs a few instructions from the computer before it can dial a number. Those instructions are frequently called AT commands, because the instructions always start with the letters AT, which alert the modem that some further instructions are on the way. Subsequent • ^ j ,^ instructions tell the modem to dial the next digits it receives with rotai)' pulses (like a rotary dial phone) or tones (like on most pushbutton - -'^ phones). The command that gets a modem to dial with tones is 'ATDT," You may send a string of instructions about how the modem should behave during and after dialing some digits after a single AT command. >■ For instance, on the Hayes 2400 baud modem, you can soften the ■ • loudness of the modem's internal speaker by sending the LO (that's L ■' plus a zero). The complete command would then be "AT LO DT" ■ f ' w": Another bank of modem instructions lets you adjust Internal modem ■ settings called registers. While these are largely fine the way they are i^vi ' i' when you turn on the modem, one register in Hayes compatible modems, called S7, should be adjusted to facilitate using the modem strictly as a dialer for voice calls. This register controls how long the modem stays on the line after it dials the number. Normally, it sticks - .. .-^ around for up to thirty seconds, depending on your modem brand. For . HjrperCard dialing, however, it is helpful to set this register to one , second. You can do that by adding the command S7=l. What this of. -. ' means to the user is that he must pick up the phone within one second of the modem finishing dialing (of course, he can pick it up before or during modem dialing, as well) , Modems aren't picky about the order in which these commands ' ■ arrive, nor whether any spaces come between them, as long as the AT • command comes first. Therefore, one useful set of modem parameters you can send to a Hayes-type 2400 baud modem would be aii, , . ''ATS7=1L0DT." If your modem does not have a volume control command (the Hayes 1200 baud modems do not, for instance), you can ■■^^ ■ ' shorten the command to "ATS7=1DT," Consult your modem manual ' "''I r- for other commands and register settings you may wish to make with '■ a HyperCard Dial command. : . -raiyt Action Commands 427 dial "(212) 555-9099 " > ^ dial "555-1526" with modem "ATS7=1DT' dial line 1 of field "Phones" with modem "ATDT' dial empty with modem "ATH" - force hang up Too Tut It: So you don't accidentally dial long distance numbers or annoy your feUow townspeople, use your own telephone number for the following command experiments. You'll only get a busy signal. If you don't have a modem, the modem experiment (the last one) won't work. Type these commands into the Message Box in any stack but the HyperCard Phone stack. dial "555-1212" - you'll hear tones from your Mac speaker put "555-1212" into temp dial temp dial temp with modem "ATS7= 1 DT' send to Puhpose: Sends a message (usually a system message) to specific objects not in the regular hierarchy of the current script. When to Use It: The Send command is one of those that grows on you as you learn more about HyperTalk and how to apply it to your applications design. It turns out that there are times in the design of a HyperCard stack when you wish to initiate an action that is already defined in an object. For instance, let's say you have a button on a card diat creates a new card In the current stack and background when you click it. You may discover that every time you come to this stack from one particular stack, you always click that button to create a new card; when you come from other stacks, you don't usually want to create a new card, because you'd rather browse for existing information. Wh^t you want, then, is for the script that brings you from that one stack to click that new card button for you. That's exactly what the Send command can do. In this case, the script would start with a command to go to the second stack; then comes a message that instructs HyperCard to send a mouseup message to that new card button. As far as that button is concerned, it appears as if HyperCard has sent a mouseUp message because of a clicking of the mouse button. Instead, it's more like a "paper" command, just as some communities have "paper streets" that exist on the maps but not on the ground. 428 HyperCard's Programming Environment In other words, the Send command lets you "play HyperCard" by sending system messages to any object you like, regardless of the location along the hierarchy of the script that sends the message. Another way to look at the Send command is that it lets you set up what some computer users know as macros, in which the script takes over for human physical action. Parameters: Any valid HyperTalk message will suffice for the parameter is the name of any valid HyperCard object: button, field, card, background, stack, Home, or HyperCeird. You may refer to an object by name, number, or id, and you must be specific about its location in the stack. Examples: ' : send "mouseUp" to button "New Card" send "resume" to stack "Home" < . send "mouseEnter" to field ID 5231 send "doMenu Quit" to HyperCard You Try It: There's little need to issue the Send command from the . Message Box. but you can use it here to see it in action. You'll be sending • ' '•- some mouseup messages to several buttons around the stacks sup- plied with HyperCard. From the Home card, type the following mes- sages into the Message Box: ' ' " send "mouseUp" to bkgnd button "Next" - to next card •'; send "mouseUp" to bkgnd button "Prev" - to previous card ■J^' ' send "mouseUp" to bkgnd button ID 3 --to Address send "mouseup" to bkgnd button "Return" Purpose: Carries out HyperTalk commands located in the first line of a container. When to Use: Because HyperTalk scripts are strictly lines of text, - ; , HyperCard can also build the equivalent of a script inside a container, ^ J like a variable or field, for later execution. As an example, you may guide a user through a setup card at the beginning of a HjrperCard application. Depending on various choices the user makes on these cards (by clicking screen buttons), the scripts Action Commands 429 inside these buttons build a HypeiTalk message in a container like a global variable or a field in the first card. When the user is finished making the various choices, he can click on a button labeled "OK" or "Do It" or s omething similar. The script for that button contains a Do command pointing to the text in the container holding the command line. HyperCard sends the message Just as if it was in an object script. Parameters: The instructions for the Do command must be in a single line of a container, most likely a field or variable. You may use all possible field names and numbers to identify a field that holds the instructions. - - . , — Examples: , do field ID 6706 do second line of third field of card "Preferences" do field "Do It" of card ID 3001 do format -- format is a global variable You Do It: You cannot issue the Do command from the Message Box. Instead, create a card button on a blank Address stack card. Place the script do field 1 into the button's mouseUp handler. Hien type each of the following commands into the first line of the top field and click the button. put 100 into field 2 i ..f^v^f-,, . ' V^ multiply field 2 by 50 ' ' ' " divide field 2 by pi „ , • : . , ; beep 3 » . • , : ■ go card "Stacks" of "Home" ... . . i.,,. ., - .. ' Experiment with other commands in lines of field 1 and click the button. choose tool oi- ; . , r Purpose: Selects any too) in the Tools palette. ' . When to Use It: The Choose command becomes very Important when your scripts need to access painting or object tools for the browser. The commands are the electronic equivalent of clicking on a tool in the Tools palette. When you design one or more Choose commands into a script, be sure you return the active tool to the Browse tool before ending the script. It's not a nice thing to leave a potentially inexperienced stack user In a tool other than the Browse tool , because he may be hopelessly lost and unable to click buttons. 430 HyperCard's Programming Environment You'll also use the Choose command when your script creates or selects a field or button (with the doMenu command) . Creating a new field or button automatically changes the tool to the Field or Button tool. The script should choose the Browse tool before returning control to the user. If you find that one of your scripts or someone else's script leaves you dangling in a tool other than the Browse too, type Comrnand-j Tab to choose the Browse Tool from the keyboard. Pakai«cters: For the Choose Tool command, you must enter the cor name of the desired tool into the parameter. Following the ' order of the tools on the Tools palette, here are the official names of each^ tool browse button field select lasso ' pencil brush eraser line spray [can] rect[anglel round rect[anglel : bucket oval curve text reglular] polygon polygon Always be sure to include the word "tool" at the end of this command. Examples: choose oval tool choose browse tool choose field 3 tool field 3 contains tool name You Try It; To demonstrate the Choose command, tear off the Tools j palette from the menubar and watch various tools become selected as ] you type the following messages into the Message Box: choose button tool choose field tool choose bucket tool ^ . choose lasso .;- ■.'.:,,,;{, , choose lasso tool choose rect tool choose rectangle tool ' ' n choose text tool ; ! . -ii ' ' choose browse tool : ;-; -z-'n. - , . click at [ with ] EHirpose: Performs an electronic equivalent of cficklng the mouse j specific coordinate location on the screen. ■ ■ ' ■ B* ' Action Commands 431 When to Use; Whenever you wish to automate a process that normally involves clicking the mouse button with the cursor at a specific spot on the screen, the click command is the one to use. Because HyperTalk lets you select any of the tools In the Tools palette from a script, you can do so before issuing the click command. Therefore, you might develop a script that chooses the Button tool, clicks on a button to select it. and then copies the button for later pasting in another card or stack. Parameters: You must specify a screen coordinate location as a parameter to the click command. A coordinate point is represented by a horizontal and vertical measure (In pixels) separated by a comma, in the form h.v. To click the cursor at the point 100 pixels across and 175 pixels down, the command would be: click at 100,175 Because many functions and properties return locations in this h v format, you will be able to use the results of such items directly In the click command (see chapters 27 and 31). You may also specify a modifier key (Shift. Command, or Option) be "held down" during the click to accomplish the same enhancement you get when you click manually. Just add the with parameter and one of these three possibilities: ShlftKey. CommandKey. or OptionKey. You can even specify multiple modifier keys, as long as you separate them with commas, as in click at 1 00. 1 00 with CommandKey, OptionKey if' Examples: cllckatlO.lOO ; : ■ ? b. . ; ^> ; ^ ; J ■ . • r- r click at it - when It holds a valid location You Try It: Go to the Address stack and type the following messages into the IWessage Box: get location of field 1 • , a valid location at the center of the field, click at It - the cursor Hashes at the left margin get location of background button 1 -- the left arrow click at it - just as if you had clicked it yourself click at It from to [with l Purpose: Performs the electronic equivalent of dragging the across the screen. 432 HyperCard's Programming Environment , . When to Use: As you've experimented with various tools in the Tools palette and their authoring powers, youVe surely come to realize that ri^.. >; much of the stack object and graphics creation processes revolve f , . : . around clicking and dragging various tools across the screen. It turns . ; : out that anything you can do manually you can also do via a script, ' ..( ; . including painting graphics. You can literally select painting tools and tell them where to draw lines, circles, rectangles, and so on. Among the ready applications for this power is graphing bar and pie ■ chart from numbers stored in a card's text fields. With the help of a little math, you can establish graph scales or divisions in a pie chart, then ■ ' select the appropriate painting tools and instruct them to drag their '■ ' magic across the screen. You may also specify that a modifier key (Shift, Command, or Option) be "held down" during the drag to accomplish the same enhancement .■ . . ; V. you get when you drag manually. Just add the with parameter and one ■ , of these three possibilities: ShiftKey, CommandKey, or OptionKey. You can even specify multiple modifier keys, as long as you separate them • with commas, as In drag from 100, 100 to 312,320 with OptionKey, ShiftKey Examples: .-. , drag from 100,100 to 250,300 ■ '.i • drag from temp 1 to temp2 You Try It: In the following experiment, you'll be creating a pie chart piece by piece. To see how the commands influence the various palettes, tear off both the Tools and Patterns palettes, and place them off to the side of the screen. Create a new card in the Address stack, which you'll use as a backdrop for the chart. Then type the following messages into the Message Box: choose oval tool set llnesize to 2 set centered to true drag from 340,135 to 420,215 set centered to false choose line tool drag from 340, 135 to 340,55 drag from 340, 135 to 4 10, 175 drag from 340, 135 to 265, 115 choose bucket tool set pattern to 14 click at 375.95 ; fi.p - -v^:^ set pattern to 22 Action Commands 433 type set pattern to 13 click at 305,95 > choose browse tool » > •'•^^X F^E^Performs the electronic equivalent of typing text into a field or When to Use: The Type command operates dlff-erently than the Put commandwhenit comes toplacing text insldeafield.ThePutcommand places the text there In one quick lump, while Type does so one character at a time, as if a fast typist was entering the text. If you use this command to enter actual text characters Into a field, it may make for an interesting self-running demonstration, because the user could see characters being entered one at a time. A more likely application of this command is to have a script type a the flashing text Insertion pointer in the first field of the card, ready for the browser to enter information. Moreover, because the script typed a Tab character, any text that might be in that field will be seated slirdlar to the way many database program forms behave Ttie Type command is also the one you use to generate graphics text under script command . For example, you could prompt the uJer for his ^Zl u r ^"""^ UserName global property set in the Home Stack Preferences card), choose the paint text tool, click at the head of a card background, and imbed the person's name into the background ^aphlcs layer of a stack. The browser never need know about painting tools to make that happen, * Examples: type This is a demonstraUon of typing." . Z'^'. : ' ' typeuserName ' ■ . . ' 'ftt ■ ' . type 'c" with CommandKey - "Copy" command "'' You TitY It: Because the Type command usually foUows a Click Z.T m^''" experiment with the Type command St ftelH ^^^"^ Click Smmand in a hfffeirf T '^^^^^t^^ *yP^ ttlie Type command) will go into toe field. Therefore, go to the Address stack, create a blank card, and create a new card button. Enter the following script into the button and men watch what happens. 434 HyperCard's Programming Environment on mouseup r- r choose browse tool get loc of field 2 ■ click at it type "Some demo, huh?" & return & 'You said it. " get loc of field 1 ■ ■■ ' choose text tool - ; ••o ■ 'v5i?M -, click at it . .^5,,.^, , ^,^-> .^^-j > type "This is painted text." choose browse tool end mouseup •\^.<; -v' sort [ ascending I descending ] [ text I numeric I international I datetime j by sort should take place. This must be a valid field designator, referred r; r'i by field name, number, or id number. If no other parameters m - 1 in.- specified , HyperCard automatically selects the text ascending order on iiff-f the container. ; ! = An Important parameter to watch for is the one that chooses froiti text, numeric, and international sorting orders. The text choice sorts according to the ASCII value of the text in the sort field. In caseyou'w «ru-'Vi- . . Action Commands 435 never heard of ASCII (pronounced. "ASS-key"), It is a standard code rec- ognized by most personal computers for each character of the keyboard (plus some others you can't get to from the keyboard). The ASCII numbers assigned to the characters are completely Independent of their actual position in the alphabet or in the digits zero through nine The important thing to remember about ASCII sorting is that it is best used for sorting text, because it does not sort numbers according to the actual value of the numbers (an ASCII sort puts the text "144" lower than the text "21" because 144 starts with a 1, while 21 starts with a 2, which has a higher ASCII value). TTierefore, if the field on which you wish to sort cards in a stack is predominantly text, use the text (ASCII) sorting parameter. One sorting trick is worth noting. If your stack features an opening card that you'd like to be sure Is always in the front of the stack leave the sort field empty. For example, in the Address stack, on which you generally sort on the last name in the first line of the name field you can leave the first line of the field blank Oust a return character) When HyperCard sorts ascending by text (ASCII), the return character comes out about as low in the ASCII rankings as you can get. guaranteeing that card's place at the head of the stack. The number parameter sorts cards based on the correct numeric value of numbers in the sort field. A field with 200 in it will be lower than a fie d with 1200. as you would expect. If the sorting encounters text in a tield. HyperCard will place the text at the beginning of the stack (In ascending sort order) but will not perform any sorting on the text cards Sorting with the international parameter primarily affects the way characters known as ligatures are treated during a sort. In languages that contain ligatures (like ^ and oe). sorting must be treated differently than strict ASCII order. For English sorting, the text parameter is preferred. Use International sorting if the data in text fields contains ligatures and umlauted characters. If you intend to sort cards in a stack by a background field containing dates, use the dateTime parameter. As long as the dates or times in the Held are in one of the many valid date and time formats, the Sort command will make the proper conversions and evaluations while sorting the cards, but without disturbing the format stored on the cards. Dates may even be in different formats on different cards As lone as the formats are valid, (see the Convert command in chapter 23) the dateTime sort parameter will handle them properly Most of your stack sorts will be ascending, so you don't have to specify a directional parameter. But you always have the descending parame- ter avafiable if you need it for those stacks better served by a sort in this direction, - 436 HyperCard's Programming Enuironment Examples: - ,;- ■ ■'Hi sort by field "Department" ' ' - ^ sort by first word of field "Client" sort descending numeric by field "Amount Due" ': sort by last word of first line of field "Name" sort numeric by last word of field "Address" = ni; . - - - ; You Thy It: You're most likely to have the largest stack of accumulated | ! ; i , Information in your Address stack, so use that one In your sorting experiments. Go to that stack and type the following messages in the ; 1 : ' Message Box. After each message, flip through the stack a minute to see ■ how the sorting command affected the data in your stack, sort by last word of first line of field 1 -- same as the Sort -- button sort by last word of field 1 sort descending by last word of field 1 i sort by first word of field 2 sort numeric by first word of field 2 • 'i '■■ sort by last word of first line of field 1 - return to a -- usable order Open [ with] 1 ■ ..- u- Purpose: Launches any Macintosh application or document. This Is \ different from the open file command. When to Use It: Early in this book, we mentioned that HyperCard can ^ ; ■ become the center of your Macintosh World . The HyperTalk command : ./^ that facilitates building this world is the Open command. This com- mand will find its way most likely into button scripts. The buttons ^ be labeled or be styled with icons of the document or application ' ' involved. Whenever you wish to branch to an external . Macintosh document or application from a Hj^perCard stack, this is the command that gets you there. When HyperCard executes this command, HyperCard sends a sus- pend system message to the current card. It then clears itself from memory entirely, as if quitting. In the process, however, it alerts the Macintosh System File in your System Folder that when you're done with the external application, the System should hand control back t« HyperCard by restarting HyperCard. When HyperCard restarts, It sends the resume message to the current card— the card from vAiki you suspended HyperCard previously. T i Action Convnands 437 Deciding how you wish to make HyperCard the center of your Macintosh World is not an easy task, because HyperCard gives you extraordinary flexibility in design. Various philosophies will likely arise from HyperCard's launching abilities. For example, you might wish to place all your Open command buttons in a special stack containing references to your frequently used documents and applications. Or you may wish to distribute the buttons throughout your stacks- like a button leading to a relational database file from a HyperCard customer list stack. Anything is possible. You will also make decisions about how much you wish to hide the name of the application when your buttons refer to documents. Do you want to concern yourself with knowing both the document and the application that created it? Or is it enough Just to know the document name and organize your documents by document type rather than by the application that created them? Par««eters: If you wish the Open command to launch just an applica- tion (that is, no document with it), then you need to specify only the application's file name. This might prove tricky at first, depending on the applications you intend to open. The text of the application name in the Open command parameter must be identical to the application's actual file name that you see in the Finder. While capitalization is not important, special characters, such as the trademark symbol that appears in some file names, must be in the parameter text. The same goes for the proper number of spaces and other notations, such as version number (for example, "v 1.1"). If the application's file name contains special characters, like the trademark character, you have two options. One is to rename the application file in the Finder. This almost never has any negative effect on the running of the application. The other option is to recreate the special charcters in the Open command's parameter. The trademark character is, indeed, available from the keyboard. Hold down the Option key and type the 2 character from the top row of the keyboard. Other common symbols are as follows: Registered Trademark ® Optlon-R Copyright © Option-G Bullet • Option-8 You can always look for other symbols by opening the KeyCaps desk accessory. With the miniature keyboard on the screen, press the Option key and then the Option and Shift keys together to see all the characters available In most Macintosh fonts. If the character appears in an application's file name in the Finder, you will be able to recreate it in the text of the Open command parameter. 438 HyperCard's Progrartvntng Environnwnt Spaces between characters In an applications' desktop file name are sometimes not easy to discern. If single spaces between words or elements of a name don't work in your Open command's parameters, study the actual file name carefully, looking for extra spaces (includir a possible extra space before the start of the file name- sometimes pesky problem that's hard to find unless you know to look for it). Y can always select the text of the actual name in the Finder and copy into the clipboard. Then go into your HyperTalk script and paste " text into the appropriate location in the command line. That sho take care of strange characters and spaces. Document parameters must also be text (that is, enclosed in quo or from a container, such as a field) . As with the application file name, the document parameter must be identical to the actual file name in the Finder. It seems that errant leading spaces crop up more readily in file names that you create, so be on the watch for them if your script has difficulty finding a document. When speciiylng a document, you must also specify the application that originally created the document separating the two parameters with the word "with." Although you may be setting up a HyperCard "front end" to your documents to disguise the applications that control your documents, you'll have to make the connection once, as you create the script that opens the document, After that, you can forget which application was used to create document or template. It's also important to keep in mind that when you put a new document or application into an Open command script, the Home Stack's Documents and Applications cards must contain the paths to the files. If the flies you specify in a script are in new folders, be sure to add paths to those folders in the Look for Documents In... and Look for Applica- tions In... Preferences cards. Of course, If you specify the complete pathname in the command's parameters, you won't have to wony about the contents of the Preferences card, because HyperCard wli automatically read the pathname from the script. Examples: open "MacPaint" , ; , open "Hard Disk:Appllcations: Excel" open "No. 10 Envelope" with "MacWrlte" open field "Title" with "Word 3.0" . open line 4 of field 2 with "More™ " You Try It: Without knowing which applications and document you have stored on your disk(s), we can't show you precisely how experiment with the Open command. All we can say is to use the a 3 y!' Action Commands 439 your own from the Message Box. You can do this while viewing any card m any stack. Remember to use quotation marks around the text of each parameter. Quit each application to return to the card from which vou left HyperCard. Open printing [with dialog] PJ^"* . [ all I cards ] I I this ] Close printing ^ , Purpose: Set up a print Job that queues individual cards for printing as if a single stack. ^ TO Use: There will be many times in your stack design when you ^^ 1 want to offer your users the opportunity to print selected cards within a stack or across multiple stacks. While you can easilyprint each card, one per page with the doMenu "Print Card" command your user loses the many printing effects available in the Print Stack dialog box such as multiple cards per page, split page printing, and so on The Open Printing, Print, and Close Printing commands let you send specific cards to the printing queue so they print as If they were all in a single stack. Pahami^rs: When the Open Printing command executes, there is a pause for a few seconds while HyperCard's printing system gets set to T^'^iul^^l ^^^^^ t° P'^nt- If the Open Printing command specifies the with diatop parameter, then the Print Stack dialog appears, allowing he user to specify the way the cards should be printed out and whether there should be a header printed on each page. -nie script then queues cards to print by either going to the desired cards and issuing the Print this card command, or printing a set number 01 contiguous cards, or printing individual cards denoted by their id numbers and stack locations. If the user selected half-size cards in the Print Stack dialog box. HyperCard will begin printing as soon as eight cards have been selected for printing. At the end of the print Job, your script should send the Close Printing command. If, for example, you have selected printing eight cards per page and only five have been selected. Close Printing will tell HyperCard to print the page as currently assembled. Close Printing also makes sure HyperCard closes down the printing system correctly. Examples: open printing with dialog ^ v . . - . print 12 cards . : . 440 HyperCard's Programming Environment print this card , print card ID 4988 -j - close printing • : <•• ;.;■« uJi . );if;qt! wa?^-; i You Try It: From the Message Box, you'll still be able to experiment mth these commands. In fact, you'll see one particularly beneficial aspect of them from the knowledgeable HyperTalk programmer's standpoint. Once you open the printing job, control of HyperCard returns to you, so you can navigate through your stacks as if nothing was in the way, When you reach a card you wish to print, simply type print this card into the Message Box. HyperCard places that card in the queue. Let's tiy it now. When the dialog box comes up, select half-size cards. open printing with dialog ^ ^ go Home print this card . go previous " _ , . ., ri • , print this card ' ■ ' _ . ' go to stack "Help" ' ' print 3 cards close printing ^ ' ^ ■ ' r. . CHAPTER 23 Arithmetic Commands While math is often a programming roadblock for nontechnical folks basic arithmeUc shouldn't be. The commands in this chapter are simple arithmetic- operaUons your scripts perform on numbers stored in containers. to Purple: Adds one number (or number in a container) to another number already In a container. When to Use It: Any time you need to sum two numbers, use the Add command. Note that the result of the addition operation Is put into the destlnahon container: You are adding one number to the second, merefore if you add the number in field 1 to the number In field 2 (odd Md 1 to field 2i, nothing will change in field 1. but field 2-s content will become the sum of the two numbers. The original value in field 2 will no longer be stored or retrievable. If your script needs that original value t ;T^" ""^'^ ''^"^ ^ lo^^l variable before perforining tne Add command. ° The Add command is a completely separate kind of addition than what you have available by typing in an addition fonnula Into the Message Box (chapter 1). If you were to include a script line such as iO + 50 HyperCard would not know where to put the result of the addition mat s why the Add command exists: so that you can not only add two 441 442 HyperCard's Programming Environment numbers but hold onto the result for display in a field or for fiirther arithmetic, pARABiETERs: Both the and parameters may be containers of any type. The most common containers you'll use with the Add command are variables and fields. Additionally, the parameter may be any arithmetic expres- sion, such as a number or a math formula that evaluates to a number (for example, 4*5/ (field "cost" +11) or functions like the second^. One way to test whether a formula evaluates to a number is to type it into the Message Box (if the formula refers to fields, make sure typical data is typed Into the fields of the current card). If you type In the formula, press Return, and see a number, then you're all set to Include the formula wherever an arithmetic expression is allowed, as in the parameter of the Add command. Examples: add field "Item 1" to field "Total" add field ID 19084 to temp - temp is a local variable add field 1 + 100 to field 6 add temp to field "Sura" add 1 to counter -- counter is a local variable add tempi to temp3 summing two local variables You Tbt It: Use fields of a blank Address stack card to work with tht following experiment. Start out by placing the values 1 0 and 20 Into the name and phone number fields, respectively. Then type these com- mands into the Message Box: put 0 Into var — Initializes global variable "var" add field 1 to var var -- var now has a 10 stored in it add field 2 to var "f* add var to field 2 ^' add field 1 to field 2 ^ add 100 to var i--:i:c-an ur. • . ..:>■ var -- var is now 130 add var to field 1 subtract from Purpose: Subtracts one number (or number In a container) fm '-' another number already in a container. GW! ....... . .. hhAo; Arithmetic Commands 443 When TO Use It: Any time you need to subtract two numbers, use the Subtract command. Note that the result of the subtraction operation is put into a container- you are subtracting one number/romtSe second Therefore, if you subtract the number in field I from the number S field 2 (subtract field 1 Jrom field 2). nothing will change in field 1 but fieW 2 s content will become the difference of the two numbeS llie o^lnLI v^ue in field 2 will no longer be stored or retrievable" y"ur Sipt nt d1 Uiat original value later, you should put that value into a local vaSable before performing the Subtract command vanabie th?"^ Subtract command is a completely separate kind of operation toan what you have available by typing in a subtraction formurinto as J 00 - 50, HyperCard would not know where to put the result of the subtraction^That's why the Subtract command exists: so iat you not only sub^aet two numbers but hold onto the result for diJp^ay^ a field or for further arithmetic. ^ Parametbhs: Both the and parameters may be containers of any type. The most common container"^ youlW Subtract command are variables and fields sion tuch^^; T"'""^ parameter may be any arithmetic expres- sion, such as a number or a math formula that evaluates to a number (for ^ample, 4*5 /{field "cost" + J i; or functions like the seconZonl way to test whether a formula evaluates to a numberTs to iUnTo the Message Box (if the formula refers to fields, make sure tXa^^daS^ Sl\ur:nf "^r^"* ''y^^ tS^taut E 1 T' ^ number, then you're all set to include the JZril ™ an arfthmetic expression is allowed, as Si Se parameter of the Subtract command. EXAHFLES: subtract field "Discount" from field "Subtotal" ' ' subtract field ID 2080 from temp - a local variable subtract field 1 + 100 from field 6 subtract temp from field "Days To Go" subS^I I ^'T r""^"' a »°<^^1 variable subtract tempi from temp3 --two local variables Tou TjT It: Use fields of a blank Address stack card to work with the Se~i.?T' r P'"'^^^ me name and phone number fields, respectively. Then type these commands into the Message Box: *- J' "-ype mese luU^ T . " initializes global variable Var" subtract var from field 2 - var still has a 25 stored In It 444 HyperCard's Programming Environment subtract field 1 from var var ~ var is now -475 subtract var from var var — var Is now zero subtract field 2 from field 1 subtract var from field 1 multiply by Puhpose: Multiplies one number already In a container by another number (or another number in a container). When to Use It: Any time you need to multiply two numbers, use the Multiply command. Note that the result of the multiplication operation r n Is put into the destination container— you are multiplying one number by the second. Therefore, if you multiply the number in field 1 by the number in field 2 (multiply field 1 by field 2i, nothing will change in field 2 . but field 1 's content will become the product of the two numbers. Tlie ' ' original value in field 1 will no longer be stored or retrievable. If your script needs that original value later, you should put that value into a local variable before performing the Multiply command. The Multiply command is a completely separate kind of multipllca- " ' ' tion than what you have available by typing in a formula into the Message Box (chapter 1). If you were to include a script line such as JO *50, HyperCard would not know where to put the result. That's why Multiply command exists: so that you can not only multiply numbers, but hold onto the result for display in a field or for arithmetic. Parameters: Both the and parameters may Ik containers of any type. The most common containers you'll use with tk Multiply command are variables and fields. Notice that the order destination and source parameters is the opposite of the Add cod- mand. Hie destination parameter (that is, where the result lands) istl« first parameter. • " ■ * j ■ «• " The parameter may be any arithmetic expression, such si a number or a math formula that evaluates to a number (for exampk, 4*5 / (field 'cost" + 11) or functions like the seconds] . One way to test whether a formula evaluates to a number is to type it into the Message Box (if the formula refers to fields, make sure typical data is typed Inti the fields of the current card). If you ^e in the formula, press Return and see a number, then you're all set to Include the formula wherever an arithmetic expression is allowed, as in the parameter of the Multiply command. Arithmetic Commands 445 Examples: , multiply field "Subtotal" by field "Sales Tax Rate" multiply field ID 500 by temp ~- temp is a local variable multiply field 6 by field 1 + 100 multiply temp by field "Sum" multiply tempi by temps -- two local variables You Try It: Use fields of a blank Address stack card to work with the following experiment. Start out by placing the values 25 and 100 Into the name and phone number fields, respectively. Then type these commands into the Message Box; put 5 into var multiply field 1 by var var multiply var by field 2 var multiply var by 0 var multiply field 2 by field 1 — initializes global variable "var" -- var still has 5 stored in it — var is now 500 -- var is now zero divide by Purpose: Divides one number already in a container by another number (or another number in a container}. When to Use It: Any time you need to divide two numbers, use the Divide command. Note that the result of the division operation is put into the destination container: You are dividing one number by the second. Therefore, If you divide the number in field 1 by the number in field 2 {divide jisld 1 byjield 2l, nothing will change in field 2. but field I's content will become the quotient of the two numbers. The original valuQ in field 1 will no longer be stored or retrievable. If your script needs that original value later, you should put that value into a local variable before performing the Divide command. The Divide command is a completely separate kind of division than what you have available by typing In a formula into the Message Box (chapter 1). If you were to Include a script line such as 10/50. HyperCard would not know where to put the result. That's why the divide command exists: so that you can not only divide two numbers but hold onto the result for display in a field or for further arithmetic. Parameters: Both the and parameters may be containers of any type. The most common containers you'll use with the Divide command are variables and fields. Notice that the order of 446 HyperCard's Programming Environment destination and source parameters Is the opposite of the Subtract command. The destination parameter (that is, where the result lands) is the first parameter. The parameter may be any arithmetic expression, such as a number or a math formula that evaluates to a number (for example, 4*5/ (field "cost" + 11) or functions Itke the seconds]. One way to test whether a formula evaluates to a number is to type it Into the Message Box (If the formula refers to fields, make sure typical data Is typed into the fields of the current card] . If you type in the formula, press Return, and see a number, then you're all set to include the formula wherever ' an arithmetic expression Is allowed, as in the parameter of the Divide command. EXAMPI£S: divide field "Average" by field Total Number" divide field ID 9007 by temp -- temp is a local variable divide field 3 by field 2 * 100 divide temp by field "Subtotal" divide tempi by temp3 - two local variables You Try It: Use fields of a blank Address stack card to work with the following experiment. Start out by placing the values 5 and 1000 into the name and phone number fields, respectively. Then type these commands into the Message Box: put 10 Into var -- initializes global variable "var" divide field 1 by var var -- var still has 10 stored in It ?biv ;C divide field 2 by var • i divide var by 0 ;ji T var -- var is Infinity- you can't divide by zero = divide field 2 by field 1 convert to Purpose: Converts date and time to formats for calculation and display, ' ' , When to Use It: Used primarily in conjunction with date and ttat ■ functions (chapter 30) , the Convert command Is a gateway to timeand date arithmetic, like finding the days between two dates, time zone conversions, and so on. HyperCard offers seven different formats fof displaying or storing time and date information. All dates, however, must be since January 1, 1904. >• : Notice that the conversion takes place in the container. If you have : ? a date in a field and convert it to seconds for some calculations, the fleki Arithmstic Cormnands 447 contents will change from the traditional date to an enormous number of seconds. Therefore, perform conversions in variables inside scripts. Parahetehs: Hie first parameter, , is any valid HjrperCard container. Typically you'll work with conversions behind the scenes in variables rather than out in the open in fields. HyperCard's date and time formats in the U.S. version are as follows: Format Name Example The seconds format is the total number of seconds the date and time you're converting represents since 12:00:00 a.m. on January 1, 1904. That's the time the Macintosh clock uses as a base reference point. While conversion to the short date always shows slashes between month, day, and year items, you may enter a date with h3T>hens as separators, as In 1 1-17-87. The Convert command recognizes this as a valid short date. The abbreviated date format may be referred to In diree ways: abbreukited. date, abbrev date, and ohbr date. Any one of those three format names is valid. Long and short times show am and PM when you select the 12-hour setting In your Control Panel. Other- wise, all times are shown in 24-.hour time (sometimes called "military The dateltems format is one you'll use frequently in date and time arithmetic. The items are, from left to right, the year, month, day, hour, minute, second, and day of the week (Sunday =1). You may add to any item, even If the result seems unusual (for example, the 35th day). Upon conversion to another format, the proper date and Ume are computed. You may not. however, subtract from items when the result is negative (or zero for the date Items). If you need to subtract dates and times from each other, it is best to convert everything to seconds before subtract- ing; you can then reconvert to a more recognizable format. seconds long date short date 2631100380 Tuesday, November 17, 1987 11/17/87 Tue, Nov 17, 1987 1:16:03 PM or 13:16:03 1:16PM or 13:16 1987,11.17,13,16,3,3 abbreviated date long time short time dateltems time"). . CHAPTER 24 Object Manipulation Commands ^rtain^liS^ THE a™ access and change a urr of informa^n about mlS^h? I ' P^cularly buttons and fields. The commands that W^e ?iso aS? "^J^*^* manipulation commands We ve also added commands that aflfect HyperCard global variables TfThT^^l! T'* ^^"'^ "^"^^ °f For the sake object uXlTa -g-i-^on, we'll temporally cover them with our Ude menubar I I h , ; Purpose: Hides screen objects from view. J^nHr^'r ^ !!?^' designing is best served by occupying * "yPf ^"do^- may wish to have the stack hldeSf Hid?M.'*'r'''"^*"'^ ""^^^^^ -h-- y°" d put tne Hide Menubar command. Himngthe menu bar Is a design decision that should not be taken ifn ^^ ^.r"'^"^**'^ menubar. you assume the burden of pro^S ^navigation buttons for the user. Menu commands like tho^^fn Sf Go menu mcluding Home) will be gone once the menus are hidd«^^ Add tionally. if the stack is one that calls for the user to genemte or delete cards, you'll have to provide a way for the user to fssue^hose 449 450 HyperCard's Programming Environment commands as well. The same goes for printing and using the Edit menu's text editing choices. Fortunately, even though the menus are hidden, an experienced user may access those menu commands that have keyboard equivalents (for -■ - example. Command -V for Paste). But if you are designing a stack for others, you should not assume that the user will be so knowledgeable as to remember the Command-key equivalents for even the simplest menu item. You'll need explicit buttons or other Instructions on the screen to make up for the missing menus. Still, in a heavily graphics-oriented stack, particularly one that Is for viewing only, it may be very desirable to remove the menus. For the uninitiated computer user, even short menus may make the stack appear more complicated than it is. Additionally, if you hide the menubar with an openStack message handler, it should be your responsibility to show the menuhar with a corresponding closeStack message handler. See the Show comnMid, below, for details on bringing the menubar back into view. You may also use the Hide command to make windows (the message, tool, and pattern windows) and objects like fields and buttons disap- pear from the screen. A common application is to hide a shadow lent field that contains some Instructions or explanatory text. When tk user clicks on a button for help, for instance, the field appears on tht . ^' screen at a predetermined location {see the Show command). Thenlllf user can click on the field (provided you created it as a locked textflelffl A script In the field's mouseUp message handler then hides the fleliT Another application might be to keep a secondary set of buttons hidden from view untU the user needs them. Then, when he presses on a button that says "More," the user is presented with additional buttons. To have all these buttons visible on the card aU the dme might make the card look too complicated. By placing these less-frequently- used buttons on a secondary palette of buttons, the user can moit easily focus on the application. When the user cHcks on one of the secondary buttons, not only does the button carry out its appointHi task, but it also hides all the secondary buttons so that they're out of ' ^ the way. ' "• Showing and hiding the Message Box is another useful capability. You'll frequently design stacks that have no place for a Message Box. When such a stack opens, you'll want to place a Hide Messa^ command in th e openStack message handler, justincasetheprecedlnj stack didn't hide the Message Box upon closing. Parameters: When the Hide command is directed at the menubai, simply add "menubar" as a one-word parameter. To hide buttons and fields, refer to the objects by name, number, tx ID number. Card fields and background buttons must also include thtt Object Manpulation Commands 451 respective domain names. Remember that these target references can also come from containers, especially variables. In chapter 37 we'll show you how to use a repeat loop construction that hides a sertes of buttcms quickly, addressing each button's name with a variable As for hiding the Message Box, you can use four different names for it: message window, message box, message, or msg. Hiding the tools or patterns windows, however, requires their full names: tool window and pattern window. Examples: hide button ID 302 hide field "Extra" . -^r hide message hide button counter -- counter is a local variable hide menubar r;- hide tool window :i Yoo Try It: You can't really tiy hiding objects without also showing Uiem- otherwiseyou may forget the objects are there, and you'll be lost ^er^fore, in the following list of messages to type Into the Message Box' there will be a corresponding Show command to restore the objects to axeir original, visible status. Experiment with these messages in the Address stack. hide menubar show menubar -- you can also type Command-Spacebar hide bkgnd button 1 hide field 1 hide bkgnd button 2 , ^ . ' show tool window . ' . " r ' = : show pattern window ,. . ' > .-iJi hide pattern window ^ ^ ' 1 ' / ' : / vr-.;.', hide tool window • ■ : . . , ; ^ , , show field 1 ' show bkgnd button 2 • show bkgnd button 1 r ' n ■ S«« menubar I I < button or field> | at ] Baow [ I all ] cards Purpose: Shows menus, buttons, fields, and windows at' a desired ocatlon on the screen. Show Cards displays a set number of cards In the current stack. 452 HyperCard's Programming Environment Whew to Use It: Since menus, buttons, and fields are created as visible entities on the screen, there is little need to use the Show command for these items unless they have been hidden by a previous Hide command, As far as windows go, you'U find yourself hiding and showing the Message Box in various stacks you design, whUe the tool and pattern windows win rarely be controlled by stacks. Since you never know how someone else's stack will leave the Message Box when it closes, you should plan to write an openStack message handler that shows or hides the Message Box as your stack design requires. There will be no damage or errors If your openStack handler includes a show message command and the Message Box Is already visible. It is good practice, moreover, to Include a closeStad message handler that hides the Message Box for the next stack. The Show Cards command is a different kind of Show command, because it deals strictly with cards that csin't ever be hidden. When you show all cards, HyperCard begins flipping rapidly through the stack, flashing each card before your eyes for a quick browse. A click of the Browse tool stops the parade. The "speeding cards" icon button In ths Address stack has a shou; all cards command in Its script. You may alsa specify a specific number of cards, beginning with the card after the current card. Parameters: When the Show command is directed at the menubar, simply add "menubar" as a one-word parameter. To show buttons, fields, or windows, substitute the item's name as a parameter. Buttons and fields can be referred to by name, number, or ID number. Card fields and background buttons must also include their respective domain names. Remember that these target references can also come from containers, especially variables. In chapter 37, ml show you how to use a repeat loop construction that shows a series of buttons quickly, addressing each button's name with a variable. As for showing the Message Box, you can use four different names for it: message window, message boK message, or msg. Showing the tools or patterns windows, however, requires their full names: tool wimkw and pattern window. Additional parameters to the Show command let you establish the location on the screen of an object you wish to become visible. Locations refer to the horizontal and vertical screen coordinates. The point you establish as being the location of the object depends on the kind o( object it Is. Coordinates for fields and buttons are for the center of the object; for windows, the point corresponds to the upper left comer of the window's content region- the area Just below the window's grey tide Object Manipulation Commands 453 bar. Therefore, if you wish to show the Message Box near the top of the screen instead of the bottom, you could show the Message Box at coordinates 25,50. As with all numeric parameters in HypeiTalk, the two numbers must be separated by a comma. While HyperCard won't let you manually drag an object beyond the screen's edge, the Show At command lets you specliy coordinates well beyond the 511, 341 endpoint of the screen (including negative coor- dinates). Exercise care in setting location coordinates. Be careful in showing objects when you're not sure how they'll look on the screen. Objects will be cut off at the window's edge if you place them too close. The Message Box is a good example of why you need careful placement. If you show it at a horizontal coordinate in excess of 50, you start to lose the right edge of the box. Here's a trick to help you determine the coordinates to assign to an object. Visualize where on the screen you want the object's centerpoint (buttons and fields) or top left comer (windows) to be and place the tip of the Browse tool's index finger at that location. Type the mouseloc into the Message Box. HyperCard will return the screen coordinates of that spot on the screen. Experiment with the Message Box first, by hiding and showing the object that will eventually be controlled by a script. Keep notes of which coordinates look the best. Then include those coordinates as parameters to the Show command In your script. Examples: show menubar ' , .. ■ . --v; show message ' ' ' . ^ J ^sl' '. ,' . ' ' ^ show msg at 30,200 . ' ■ , , ' : show button ID 4676 show button george -- george is a local variable . ' show field 3 at 100,120 -^, , . . ' You Try It: We refer you to the You Try It section of the Hide command, above, for some examples of the Show command. What you can experiment with here, however, is the way you can specify a location of a shown object. From the Address stack, type the following messages into the Message Box. ■:>; -i, ^, ■yt-S'Hi get location of bkgnd button 2 -""iii > hide bkgnd button 2 ' . :••;:/> show bkgnd button 2 at 256,171 ' »v'. r^-^ u ( ; rio^; • show bkgnd button 2 at it - » show message at 0,0 , , , i . <■'. ■ ■ . • show message at 300.50 • ' " ^ ^' '.if''.. 1" '"T! show message at 25,300 ' ^ j ', / \ ^' 454 HyperCard's Programming Environment get | of ] set [ of ] to Purpose: Get retrieves object properties; Set assigns new settings ; . , object properties. When to Use It: Because Get and Set are so compleraentaiy, we'E discuss these commands together. While they work in opposite dinec- -*'■>■' tions, their treatment of parameters is nearly identical. The oi difference is that the Set command has one additional parameter. !^ ' ■ When the Get command retrieves an object property, the result of * > retrieval automatically goes into the local variable It, You may then work with the information as you would Information from any con- ■'• - tainer: Putit into afield, perform math on numeric information, mod!| ' >' the text, and so on. Both of these commands allow the HyperCard author to incorpora' c>h scripts into stacks that retrieve and modify the properties of certain global variables, stacks, backgrounds, cards, fields, and buttons, without forcing the user to get into the object dialog boxes , For example, you could establish a setup card at the beginning of a stack that ■> ' prompts the user for the way he would like certain text buttons to read or which kind of icon (from a selection on the card) he'd bke his Home button to have. The script would first use the Get command to retrlm the current settings to display on the setup card. Then, by simply typing In a name or clicking on selections, the user will have his preferences inserted into the stack with the help of the Set command script youVe carefully laid out for him behind the scenes. Virtually eveiy properh' you can set in object dialog boxes, plus several Important global, window, and painting properties, can be retrieved and modified with the Get and Set commands. Properties are discussed in detail In ^ chapter 28 ' : Parameters: All Get commands need to know the name of the propem ■ M. you wish to retreive and, when necessary, the object that has the ' property. When the property is a global or painting property, the targfi name is not needed. Otherwise, the target is one of five possible HyperCard objects or the name of a window (windov/s are nottechni- ' cally HyperCard objects) , You may refer to these objects by name number, or id number. Be sure you specify the type of object, as In | button ID 46403 | Each of the five HyperCard objects has different properties that you can l plug in as parameters to the Get command. They are listed briefly Ifi |' Table 24-1, and discussed in detail in chapter 28. i Object Manipulation CoTnmands 455 ---f ^ I ^ ^ 1 ^ I Properly Name 0 ^ CO m o E ffl autoHilite blindTyping ; brush centered > cursor . iyiy- .... .. dragSpeed • editBgknd • filled grid hilite ^ ^ icon language • ItneSize ' ■ ■;..». ■„, location • • • • lockScreen • lockText • multiple - ' ■ m'- ''^ multiSpace i - u , name : , , , , , numberFormat • pattern so v'/t- • polySides ■-'^^'V/'-^-..-- : ' -• ^-i'-v powerKeys • Jjv rectangle - • • • ; script • • • • • . ,.; scroll ■ V ' • • showLines ' Viai^:, ; ^ :-. '^^^ ' - , showName " ^. ' " ■ ■ style ' ' ■ ' ' :• • • textAlign , • : , , , ^ textFont i-i^; • • • textHelght • • • textSize ! ' • • • textStyle • • • userLevel • ? ' • i?: ■ , visible • wideMargins • ; Table 24-1. 456 HyperCard's Programming Environment Property parameters to the Set command are the same as for the Ge command. The additional parameter is the new setting you wish apply to the object. If the parameter is a text string, such as the object name or button style, place the parameter in quotation marks, as in set name of field ID 104 to "Phone Number" A number of object properties have very specific requirements a what settings they'll accept. For example, the textStyle property ■ field will accept only the styles listed in the Field Info dialog box. setting must be spelled properly in the Set command's parameter. HyperCard doesn't find a match for the setting, you'll get a message advising that HyperCard doesn't understand the arguments (that is, parameters) to your Set command. Examples: get userLevel get location of button var -- var is a local variable get textFont of field 'Name" set lineSlze to 2 set textFont of field "Name" to "Times" set textSlze of field "Name" to 18 set name of button 5 to "Cancel" You TKir It: These two commands are fun to explore because you see immediate results on the screen from your Message Box messages. Create a blank card in the Address stack and create one new bu leaving its settings to the ones supplied by HyperCard, Choose Browse tool and put a line or two of text into each of the text fields the card. Then type in the following messages, get location of button "New Button" it see the coordinates of the button put 50 into item 1 of it set location of button "New Button" to it set name of button "New Button" to "Mac Forever"' get name of button "Mac Forever" it — see the button name set hlllte of it to true get textFont of field 1 put it into temp - get textSize of field 1 ' put "-" & It after temp . , ^ * temp -- see the font and font size In a familiar format get style of field 1 ' , It ' ' Object Manipulation Convnands 457 set style of field 1 to shadow ' set style of field 1 to it Feel free to continue your experimentation with get and set. global vv-y j^. s^nv; Purpose: Initializes a HypeiT^alk global variable; alerts HyperTalk that you will be using an existing global variable in a script. WHEPf TO Use It: A global variable, as you'll recall, is a container that will hold information after a message handler ends. You Initialize a global variable differently than a local variable. When you put a number or text string Into a local variable, you've initialized It. But with a global variable, you must use the Global command to get things going. Once you initialize the global variable (some experienced program- mers might also call this "declaring" the variable), you can put Information into It or manipulate information inside it like any con- tainer. I^ter. If you wish to use a global variable's information In a different message handler, you'll use the Global command again to let HypeiTalk know that you will be using that particular global variable in the current message handler. The only rule about placing the Global command in a handler is that it be in a line above the command that uses the variable. It is better form, however, to declare all global variables at the top of a handler so you can see at a glance which globals are used throughout the handler. You should use global variables sparingly, because once you assign a variable name to it, you won't be able to use that name as a local variable without the possibility of getting mixed up. Most of what you need variable containers for can be handled by local variables. Parameters: The only parameter for the global command is any name or comma- separated list of names you wish to assign to variables. Do not put quotation marks around a variable name. A variable name, however, must be one word. That means you cannot have spaces between parts of the variable name, but you can use techniques like capitalizing each component word or using an underline character to fill in for the space. Examples: :-ir -<; )'b:i ,::" _ global hank ' ' "' ''^ -t- ' '-b^^^ global stereo l.stereo2. stereos. mono -''"'^ r^r'-^iL ^ M -i^ai global BookNumber -"«v -A global areaCode -n • ^.^.;^svc--c Muilo afiacxf 458 HyperCard's Programming Environment You Tut It: All variables you initialize from the Message Box are global variables, because there is no message handler that a variable can be "local to." Therefore, to see how you use the Global command in typical scripts, create a new button in any stack of your choice. Enter the following lines of text into the script dialog box: on mouseDown global howMany put 2 into howMany end mouseDown on mouseup .-^rtr - ,;.i>«v.r- , . , !-:. beep howMany - , ,j end mouseUp When you tiy clicking on this button, you'll get an error message telling you that the parameter to beep (in the mouseUp handler) is Invalid .That'sbecausethe global variable howlVIany was not redeclared In the mouseUp message handler. Now open up the button's script dialog box and modify the mouseUp ; - message handler to look like this: ' on mouseUp ;i^"tiO, r r ' ' global howMany ' ' ' beep howMany ■ end mouseUp When you click on the button this time, you'll hear two beeps* because the global variable carried over successfully to the mouseUp message handler, thanks to the redeclaration of the variable howMany. edit script of -^rn^ ; ^ Purpose: Opens Script Editor window for a given object. WttEW TO Use: It is unlikely that you'll openly Invite nontedml browsers to dig into your scripts, so access to the Script Editor via ' " ' ; script won't find its way into many applications. But it does bee ^hU useful when a HyperTalk programmer develops utility types of sc ■ ' ' ■ ■ ' that aid in the programming task. One such utility might search object scripts In a stack for a particular command or word. If the s finds a match, the Edit Script command wUl open up the Script for that object, bjrpasslng all the object selection and double-cli that is otherwise necessary. If your stacks are destined to be used by nonprogramming make other provisions for user-modifled scripts. Hie Set comm allows you to write scripts that modify any object script without o Object Mcuiipulation Commands 459 the Script Editor. If you can design a less-frightening Interface to the script than the Script Editor, do so. Let a script make the actual changes In the object scripts. Parameters: The only parameter to the Edit Script command is the name of the object whose Script Editor you wish to open. You may refer to the object by its name, m, or number. Just as In referring to objects with other HyperTalk commands. EXAUPLES: edit script of background button ID 4 , edit script of background "Country Maps" edit script of card field 1 edit script of stack "Address" You Try It: From the Home Card, type the foUowlng messages into the Message Box: edit script of this stack edit script of background field 1 edit script of background button "Next" CHAPTER 25 Screen Manipulation Commands / ■ iv" '>7ti r:. ; iO- - :> HyperCard gives you commands to influence the visual effect of shifting from one card or one stack to another. You also have commands that present dialog boxes on the screen, which prompt the user for informa- tion. visual [effect] [J I to black I white I " gray I inverse] . . Purpose: Controls the built-in visual effect for the next switch to another card. When to Use It: For a visual effect to Impact the switch to the next card, you must specify the effect some time prior to the next card svrftch but within the same handler. It may be In the script line just above the Go command or anyplace earlier in the script, as long as there is no intervening Go command (or Find command whose search will show a different card). Internally, HyperCard remembers the last Visual Effect command that was sent and holds that effect in safekeeping for the next time HyperCard goes to another card. But at the end of the handler (that is, at "idle" time), the visual effect is forgotten. To keep your visual effects connected to the desired card switch, it Is perhaps best to place the Visual Effect command immediately preced- ing the Go or Find command that calls up the next card. This wffl also help you find a Visual Effect command that needs editing, since It will be close to the card shfft command in question. 461 462 HyperCard's Progranvnlng Envimnment Parameters: The word "effect" Is optional In the command, but you may find it helpful in long scripts to have the longer version, because it makes it easier to find the command line with "visual effect" in it. Efifect names must be the correct name from the following list: zoom open I in Iris open bam door open wipe right scroll right dissolve zoom close I out iris close bam door close wipe left wipe up scroll left scroll up checkboard Venetian blinds wipe down scroll down Visual Effect Techniques: Be aware that the zoom open and zoom close visual effects start or end their zooming on the point of the Browse tools location when the mouse button is released. Therefore, if you have a zoom open visual effect assigned to a button at the lower left comer of the screen, the zooming look wiU emanate from that comer when you release the mouse button. Similarly, a zoom close effect would zoomfo that spot. If that's the desired effect, use it. If the stacks you create are on-screen metaphors for real-worid can! files or forms files, be on the lookout for visual effects that emulate the flipping through of the cards when browsing to next and previous cards. Wipes are often good choices for this effect. For a link that takes the viewer to a perceived lower, more microscopic level, consider the iris open visual efi'ect. The tris opens from the center of the screen. When the link action Is to a perceived higher level, use tlie opposite, iris close. This brings up an important design point. You will help your hrowser get a better feeling for navigation through the stack if you choose complementary visual effects when the link branches to a card with a different look. For example, you might consider a bam door open effeci when the browser clicks on a Help button in your stack to get to a help card. When the browser has finished the help card, he can press a "retum" button to resume navigation through the primary stack. Hif retum link should use the bam door close visual effect, the opposite of the one that brought the browser to the help card. The open and close variations of the effects help the browser perceive a distinct difference between the help system and the main part of your stack- like opening a reference book and then closing it when finished. These are useful psychological aids to help the browser successfully navigate your stack. Another parameter, which controls the apparent speed of the visual effect, is optional. Possible choices are: Screen Manipulation Commands 463 /r -f, . very slow • = ' 'V slow ' ■ fast ■:;i..;cv.>;;- -^e-: If you don't specify a speed parameter, HyperCard assumes you want normal speed. Effects may also Include an Intermediate black or white screen between cards with the optional to black or to gray or to inverse to white parameters. These options open many more visual effects opportuni- ties, such as replicating the wipe action of a slide projector. A button script for this action would be . , on mouseUp . ' ' " visual effect wipe left fast to black ' ' ' '^ : visual effect wipe right fast go to next card ; . • • end mouseUp , - > j.iT-» '.V Examples: ' i^.n^^rj- -J^rni,-. visual effect bam door right visual dissolve to black visual effect wipe up slowly visual effect iris open very slowly You Try It: You can perform the experiments here in any stack, but there's no guarantee that each of the effects will carry their full impact. That often depends largely on the graphics and text field content of the card designs you're switching between. The point here will be for you to watch closely how various effects look. Making the proper choice for your own stacks will be a matter of trial and error. Since visual effects are purged during idle time, you won't be able to experiment with them from the Message Box. Go to the Address stack and create a new card. Into a card script handler starting "on effectShow" type each of the visual effects commands separated by a go next card command line. Type effectShow into the Message Box, and watch the parade of visuM effects on the stack. answer [with [or (or ] ] ] Purpo8e: Prompts the user to make a choice from one, two, or three text buttons inside a small dialog box. When to Use It: Whenever you need to ask the user to choose between two or three possibilities or just alert the user to something, the Answer command produces Just the right dialog box (Figure 25-1) . You can ask 464 HyperCard's Programming Environment the user any question you want, as long as the question fits inside the width of the dialog box. You may specify up to three replies as parameters to the command. Each reply appears as a text button inside the dialog box, and the rightmost one is pre- highlighted for acceptance with a press of Return or Enter. Typical applications Include wamtngs, in which there might be single button with "OK" in it. Better yet, the script that produces th kind of dialog box should offer both an "OK" and a "Cancel" button so that the user can back out of a button action taken inadvertently. When the user clicks on a button, the text of the reply is put into the local variable It. From there, your script can make further decisions based on the content of that container (decision-making is ejcplainedin detail in chapter 37). The user may also exit the answer dialog without sending any reply to It by typing Command-Period. Parameters: The Answer command must have at least the parameter supplied by the author. Text for the question should be placed into the command enclosed In quotation marks. The text may also come from a container, like a field or variable, in case your script will be tailoring the question based on the content of a field in the card, The question should be less than about forty characters to fit inside the dialog box, Chicago- 12 is the only font allowed for the questions and replies Inside the dialog box. When phrasing the question, try to take the point of view of the stack's user. If the user will likely be an inexperienced computer or HyperCari user, avoid Macintosh or HyperCard Jargon at all cost. If the dialog boi is a warning, explain the consequences of proceeding. If you don't include at least one parameter, HyperCard automatically inserts one that says "OK." HjrperCard starts filling replf buttons in the dialog box from the right edge of the box. An answa command with two parameters will display the two buttons at the center and at the right of the box. You don't have a lot of room for reply text, since the width of the reply buttons In the dialog box Is fixed, and the text font is a rather robust Chicago- 12. Therefore, be brief with your replies. Try to hold them to one word or two very short words. Figure 25-1. The answer dialog box Slcreen Maniptdation Commands 465 EXABIPLES: answer "Pausing until you're ready..." answer "Go ahead and erase card?" with "OK" or "Cancel" answer "Who's your favorite?" with "Larry" or "Moe" or "Curly" You Try It: If you've been looking for the power to produce dialog boxes on the screen, this is the experiment for you. You have full access to the Answer command from the Message Box. From any stack, type the following messages into the Message Box: answer "What program are you using?" with "HyperCard" it ~ contains the reply answer "Proceed to blow up neighbor's PC?" with "OK " or "Cancel" it — contains the reply you chose answer "Take a break from this book?"wlth "Yes" or "No" or "Help" it ~ contains the reply you chose ask . <„>,w.t.<„pw ' ask password [with ] 'i^j::-'. Purpose; Prompt the user to type a text response. When to Use It: The Ask command differs from the Answer command in that the ask dialog box produces a text field in which the user may type an answer, instead of having to choose only one of the options presented with the Answer command {Figure 25-2). Incorporate the Ask command into a script when you need additional information from your user. Often, the ask dialog makes a more controllable substitute for Message Box finding. When the user types in the reply and presses Return or clicks the box's OK button, the text of the reply is automatically put into the It container. You may then retrieve the text, manipulate it, and Insert it into other containers (fields and variables most likely) at your discre- tion. Please enter your name: 1 OK I Cancel Figure 25-2. The ask dialog box 466 HyperCard's Programming Environment The Ask Password variation goes one step further. Instead of return- ing the text of the reply to It, HyperCard returns an encrypted integer representing the reply typed into the ask dialog. This feature allows an | author to buUd password protection Into a stack separate from hisom j Protect Stack system. At setup time, the stack should ask the browse ! to type a name or password, whose encrypted Integer gets stored In i j field someplace in the stack. Then, when someone tries to use the stack, i he or she must know the password, whose enciypted integer Is compared with the stored integer. Even if someone could "break Into" the stack, the password would not be there— only its encrypted j representation. ' Parauetbrs: The Ask command must have at least the parameter to the Ask command,! HyperCard presents an empty text box inside the dialog box. You may, however, present in that field a default reply, which the user may accept j or type over. The default reply is automatically selected for the m when the box appears (Figure 25-3). You may use any container as the j source of the text for the reply parameter. If the input your stack needs} must be in a particular format (like a date), you can place a sample of j the format as the default reply to show the user how to type the j information. Figure 25-3. You can specify a default string Jor the text Jield in an asfcdtalqg box. Screen Manipulation Commands 467 Examples: ask "What's cookin' tonight?" ask "Search for..." ask "Enter hourly rate:" with "25" ask "Enter your name:" with field "Name" In card "Setup" ask "Enter your blrthdate:" with "3/15/55" You TfeY It: As with the Answer dialog box, you may play to your heart's content with the Ask dialog box from the Message Box. For starters, type the following messages in the Message Box in any stack: ask "Name your favorite music performer:" it — contains the name you typed in ask "Enter your desired salary..." with '$100,000" it -- contains either $100,000 or another number you typed in ask Password "What's your name?" It contains the encrypted Integer of your reply. CHAPTER 26 Sound Commands HyperCard is capable of producing two kinds of sounds, including one you've probably heard plenty of: the Macintosh beep. The other is an entirely open-ended system that allows you to play back electronically recorded sounds from the real world. That includes real voices, sound effects, and music. beep [] . . . > ,<5 > ' Purpose: Emits the Macintosh system beep through the computer's speaker or audio port. Wben to Use It: As you've seen in dozens of examples throughout th^s book, the Beep command is often helpful in exploring the workings of scripts and commands. When placed tn strategic locations throughout a message handler, this command provides an aural clue about what's going on inside a handler as it runs. The beep tone Is a fixed one and cannot be played at any other pitch or length. You can control the number of beeps, however. Still, the Beep command Is not the one to use if you wish your HjrperCard stacks to play a tune at a particular Juncture In Its operation (see the Play command). Outside of programming and script debugging, the Beep command can be quite functional in a HyperCard application when you wish to call attention to something, like an Answer dialog box. Sometimes you 469 470 HyperCard's Programming Environment have to alert the user that he must take some action. A beep serves wdl ' as that alarm. Parameters: The sole parameter to the Beep command influences the I number of times the Macintosh beeps. You may use a plain number, any arithmetic expression (that is, any formula that evaluates to a number), or a container that holds a number. If you leave off the parameter, HyperCard beeps once. If you specify multiple beeps and find they occiu- too close togetherfor your liking, you can artificially slow do\TO the beep effect. One way would be to issue single Beep commcmds with Walt commands inter- leaved. If the number of beeps is fairly large, however, you may want to place this beep-and-wait combination in a repeat looping construction (detailed tn chapter 35). Examples: beep beep 3 beep field 'Tseeps" beep beeper -- beeper is a local variable You Try It: You may already have beeped enough, but if you'd like to hear a few more, type the following messages into the Message Box from any stack: beep beep 1 beep 5 put 2 into beeper beep beeper play [tempo l [octave] [duration] [ 1 [# I b] Purpose: Plays prerecorded sounds as musical notes at vaiying ten pitches, and lengths. When to Use It: Built into HyperCard is a rather extensive single-" music generator controlled by the Play command. What It do actually, is extract the waveform from a prerecorded sound andalJows^ you to play it through the Macintosh speaker or audio port at any tempo and note pitch you wish. In order to use this feature to the fullest, it helps to know something about musical notation, because the parame- ters are largely based on standard musical terminology. Sound Commands 471 Recording the actual sounds requires an external device called a digitizer. TTiis box has a microphone and other audio Input connectors. The unit records short segments of any sound- including real voices- as electronic signals, similar to the way digital audio on the compact disc works. These sounds need to be converted into a Macintosh resource file and added to a HyperCard stack file using a resource mover utility program. In addition to playing back the direct sound as it was recorded. HyperCard can play back any sound with a wide variation in speed and pitch. If you string together many notes in a Play command, you can literally have your HyperCard application play a single voice of music for the user at key places in your stack. HyperCard comes equipped with the following sounds already Installed as resources on the Home stack: Harpsichord ' Boing ■■ ■ = Silence ■ , ■ ■ : Dialing Tones > PARABiETBRfl: The Play command has what may look to be a complicated set of parameters. Not all of them are necessary, although they are if you Intend to make music with digitized sounds. The only required parameter is the name of the voice the Play command should use. The name must be in quotation marks and must match the spelling of the resource name containing the waveform. Tempo is optional. If none is specified, HyperCard uses the last one set (or a medium value of 200). It's difflcult to attribute a tempo value to the more tradiUonal way of measuring tempo, beats per minute. You may wish to assign the tempo as the last parameter you insert into the Play command. Get the notes down first, then work on adjusting the tempo. Calling for notes Is as simple as using the familiar letters (a, b, c. d. e, f, and g) of the scale. Notes may be natural (no accidental parameter), sharp (#), or flat (b). If you don't specify any octave for the first note in a Play command. HyperCard plays in the middle octave (around middle C), which has an octave value of 4. Once you set an octave value In the command, it remains in effect for subsequent notes in the same command line or untU you specifically change it. An octave value runs from c through the next higher b. Figure 26-1 shows how the middle three octaves break out according to HyperCard octave values. Notes are also assigned note numbers, with 60 being middle C. Each number up or down represents one-half step. If you use note numbers, you needn't bother with octave and accidental parameters. 472 HyperCard's Prograrrardr^ Environment Middle C I \ \ I : i> - octaves octave 4 octave 5 Figure 26-1. The middle three octaves of the Play command are tfie ones wtih the best audio quality on the Macintosh Plus speaker. Note duration may range from a whole note to a 32nd note, notation for the duration parameter is as follows; w whole note ■ ' . '■' half note ' , ' ' q quarter note e eighth note . s". sixteenth note ■ t thirty-second note You may extend the duration of a note by one-half Its value by typ a period after the note value, as in a dotted eighth note (e.). To turn a note into a triplet at the current tempo and note value, add a 3 to the note duration. To play a continuous musical melody, string all the notes of thf melody together after a single Play command. A quarter note scale from j middle c to one octave above middle c (c') would look like this: ;- . play "boing" tempo 200 "cq d e f g a b c5". Notice that once an octave and note value are set, they remain in effect throughout the rest of the Play command, unless either of those values changes for a note. Treat each note as a single entity, no matter h many parameters It requires. For example, an eighth note f-sharp octave below the middle octave would be f#3e. If the sound recorded by the digitizer is self-contained, like a sound effect or a person's voice you'd like to play at the original pitch and speed, then simply issue the Play command with the name of the sound. No other parameters are necessary. Sound Commands 473 ExAMPixs: play "boing" play "breakingGlass" play "harpsichord" tempo 120 "ce e g c5 e g4 c5 e" You Try It: We could go on all day providing you with ditties to type Into the Message Box, but we'll give you only a couple. If you're musically inclined, you will knovi^ how to apply your own music to the Play command and work up a single-voice symphony. Experimenting with the Play command in the Message Box Is also the way you should develop Play commands that will eventually go Into stacks. By typing the command there, you can Immediately hear it and make any changes to Iron out the clinkers. Hien copy the finished command and paste it Into your script. So have fun, ^d type the following messages into field 1 of an empty Address stack card without pressing Return untU you've typed the entire command. Then create a new card button with the mouseUp handler that reads dojield 1 and click the button to make these commands work. play "harpsichord" tempo 180 "a es eq es f# g# a b c#5q a4s aq g#3s a b aq ew" play "Boing" tempo 240 "c#4e d# f f# a#t g#e g g# f f# g# a# b d#5t c#5e c c5# bb4e. be d5t d#e g#4 bb4t be f . . gt g#e c# et fe f# at a#e c# et f#e a3# c4t c#e f#3w" CHAPTER 27 File Mcinipulation Commands Although HyperCard is a powerful environment unto itself, it does not operate in a vacuum. You can Import information from other applica- tions and export HyperCard information to other documents. These abilities are carried out by the file manipulation commands. So Is the ability to print any Macintosh document (for which you have the application on disk) from within HyperCard. open file until ) for i ,; ,. , Purpose: Imports text data from an external flle into fields in the card, I When to Use It: Importing text from external files Is particularly useful i if you have database or spreadsheet Information you'd like to convert \ j' to HyperCard. This Is not a simple operation ifthe Information consist! j / , ... of many fields per card. We explain more about this ability of HyperCani i in Appendix A. ; A good place to start learning about the Read From File command Is I y^. the following Import Text button. The script in this button is a basic j , . skeleton of the kind of script you use to retrieve data from an outside ; file and put it into a stack's cards. The script reads as follows: ' File Manipulation Commands 477 on mouseup ask "Which file do you wish to import?" with "Transfer Text" if it is empty then exit mouseUp put it into flleName open file flleName ' i^-^f^ »' r -. ■ - go to last card ^ i-.: ij^^^ ^ ..' repeat forever doMenu "New Card" ' read from file flleName until return 1/ if it is empty then ] go to first card ' ' close file flleName ; ' exit mouseUp . - • .. , • else put tab Into last char of It " * * ' repeat with x= 1 to the number of fields put char 1 to offset (tab.it) of it into field x , ,^ . delete last char of field x delete char 1 to offset (tab, it) of it end repeat , end repeat > \. ..ift end mouseUp The basic construction reads a full record (up to the return character) into memory at once. When there are no more records to import, the handler ends. In the meantime, external data from each field is placed into its own card field (minus the tab character) and deleted from memory (field by field) with each journey through the loop. Parameters: The parameter must appear in quotation marks. If you dont specify a path name to the file, HyperCard looks through only to the root (topmost) level of the current disk for the file name. You may also detail a different path as part of the file name parameter. Importantly, the file must have been opened with the Open File command earlier in the script for this command to work. As with any text parameter, the file name parameter may be straight text or text from a container. When reading from a file, this command needs to know when to pause gathering information so that it doesn't overload a card or field. The command may read until it encounters a particular character or a fixed number of characters (1 byte = 1 character). A is a special character in a file that sets apart Individual items. The most common delimiter character used to separate field information in database and spreadsheet files is the Tab character. Hie character used to separate one group of Information from another group (in HyperCard terms, one card from another card) 478 HyperCard's Programming Environment is the Return character. In other words, these characters are stored In ; . the file along with the textual Information. By specifying what the delimiter characters are In the file, the Read From File command wUl know when to stop filling information Into a field and to proceed to the next field on the card. Then your script can check for the dehmiter character that means all the fields have been filled and it's time to make a new card. Study the skeleton script, above, and follow the logic of Its execuUon, Ejeahpixs: ■ ' ' read from file "Sales Data" untU tab read from file temp until return — temp is local variable read from file "My File" for 40 You Try It: Combine experiments on the Read command with experi- ments on Its counterpart, Write, below. write to file Purpose: Exports text data from a HyperCard card to a Macintosh text file. When to Use It: Exporting text to external files is particularly useful If you wish to convert HyperCard information to data usable in external ' ■ •■ >■ database or spreadsheet programs . This is not a simple operation If the information consists of many fields per card. We explain more about this ability of HyperCard in Appendix A. A good place to start learning about the Write To File command Is the following Export Text button script. The script in this button Is a basic skeleton of the kind of script you use to send data to an outside file. Hit script reads as follows: • . on mouseup n a,- in- - ^ i- ■ ir-iwC • put the short name of this stack && " text" into fUeName ask "Export text to what file?" with fileName ■ 8 ' if it is empty then exit mouseUp put it into fileName ^ , . - ; . open file fileName go to first card . r ; repeat for the number of cards put empty into tempRecord ; ,• , ; ; repeat with x= 1 to the number of fields • hv put field X & tab after tempRecord J . end repeat ni;;7>>f'nt:lfii « ' V.u Put return into last char of tempRecord File ManipukLtton Convrumds 479 write tempRecord to file flleName go to next card ' - ^ end repeat ^ "s ' -ir . w close file flleName ■ • r ; « ' • ; > end mouseUp The basic construction requires the script to store individual Hyper- Card fields in a local variable, inserting a tab character at the end of each field. When all the fields In the card are stored, the script adds a return character, writes the contents to the file, and goes to the next card In the stack to repeat the process (the repeat structures will be explained in chapter 37). You can use the basic script for a great deal of the exporting tasks you'll need in HyperCard. If you need further help in customizing the script for special purposes, consult Appendix A. Parameters: The parameter Is the name or number of a field. HyperCard must know which field's informaUon is to be exported for each card. The parameter must appear In quotation marks. If you don't specify a path name to the file. HyperCard places the file in the root directory of your disk. You may also detail a different path as part of the file name parameter. Importantly, the file must have been opened with the Open File command earlier In the script for this command to work. (.•-;.-.•-;.; . As with any text parameter, the file name parameter may be straight text or text from a container. Unlike the Read command, the Write command does not include deUmlter characters to outgoing text. Your script must write these, as indicated in the sample script. write to file "Mailing Labels" ' ' ' ' 1 . write to fUe temp - temp is a local variable " , You Trt It: The best way to try the Write and Read commands would be to use the button scripts provided above. That will give you an idea of the way a script can repeat the procedure. In the meantime, here's a simple way to write out one field from an address card and then Import it back into another card. Before you begin, be sure you have no existing dtsk file called "New File." If you do, this experiment will erase it. Type the following messages into the Message Box from a filled-ln card tn the Address stack: open file "New File" write field 1 to file "New File" write tab to file "New File" 480 HyperCard's Programming Environment close aie "New File" ^itr-' * ' doMenu "New Card" vy open file "New File" read from file "New File" until tab put it into field 2 close file "New File" print with y:-. , 'Jo- in; >' j . Purpose: Prints a file generated by another Macintosh application. When to Use: The Print command gives you the opportunity to recreate from within HjrperCard the same Print command available in the Finder, That command lets you select a document and print it directly fix>m the Finder, without having to open the document first. When you issue this Print command from a HypeiTalk script, HyperCard launches the application and loads the document for printing. When it is finished printing, the application automatically quits, and you come back to the place in HjrperCard from which jou generated the Print command. Parameters: Two parameters are required for the Print command. Tat first is the name of the document file you wish to print. The file name must be in quotation marks or be in a container. HyperCard looks to the Documents card in the Home Stack for the possible pathnames fw documents to search for the file. You may also specify a full pathname as the file name parameter. The second parameter is the name of the application program that created the document you wish to print. Application names mustbein quotation marks or in container. HyperCard looltB to the Application! card in the Home Stack for the possible pathnames for applications, or you may specify a full pathname for the application parameter. It's important to remember that the application name. parameter must match the precise name given the application in the Finder. Thai means all special characters, Hke the trademark symbol, must be In the parameter. Such special characters are available from the keyboani, usually in Option -key combinations. Some of the most popular ones are: Registered Trademark ® Option-R Copyright © Option-G Trademark ™ Option-2 BuUet • Option-8 File Manipulation Commands 481 Examples: print "3/12 Letter" with "Word 3.0" print temp with "Excel" -- temp is a local variable print "Report" with "Works" You Try It: Since there's no way for us to know the documents and applications you have on your disk, you'll have to experiment with this command on your own. Just be sure you include the quotation marks aroimd your document and application names, and watch out for special symbols (and version numbers) in the actual names of applica- tion programs. This concludes the tour of the HyperTalk command set. In the next chapter, we look at the many properties that you can inspect and set through HyperTalk. CHAPTER 28 HyperCard ^ Properties ^ ^ ^ - In cHAPreR 24, we introduced the concept of properties, which can be retrieved and set by the Get and Set commands, respectively. Now you'll see precisely what these properties are all about and how useful they can be when you tiy to automate processes for nonprogramming HyperCard browsers. Virtually every setting you can make In an object dialog box or In the HyperCard Preferences card can be set from a HyperTalk script. The importance of being able to "get" a property is that you can read what It currently is from within a script. If the setting is different from what you want It to be (something the script can determine with an if- then-else control structure), the script can make the desired setting. You should also endeavor to reset properties to their original settings' after you've modified them for the purposes of a single message handler. When you use the Get command to retrieve a property. HyperCard places the current reading Into It. From there, your handler may make whatever decisions or conversions are necessary inside that variable. HyperCard properties fall Into eight natural classes, although some classes have many more properties than others. Well follow this classification system, working our way from the most "global" to the nan'owest property settings, those having to do with fields and buttons. HyperCard lets you be terse or more English-like in your syntax when referring to properties that have parameters following them. On the terse side, you can say things like get loc of Message; but it may be more 483 484 HyperCard's Programming Environment natural to say get the location of the Message Box. In other words, yo may put the in front of a property name, and in front of any referen to the Message Box. If the property has no parameters, then the is required before name of the property, except in Get and Set command lines. It's a g idea to get in the habit of using the with such properties, because th behavior is very similar to functions, as you'll see in a later chapt Global Properties In the global properties categories are those that can have a major effect on the operation of a stack or how the user interacts with a stack. Ifcu mi^t think of these properties as properties of the HyperCard object In the hierarchy of objects. The settings in the Home Stack's Piefer ences card set global properties. blindTypiXlg Purpose: Controls the ability to type into a hidden Message Box. Wh£n to Use It: When you check the Blind Typing checkbox in Preferences card, the blindTyptng property is set to true, meaning that you can type into the Message Box even If it is not showing on the screen. Beginners should probably keep this property set to false, because it may be disconcerting to type and not get any visual feedback that the Message Box is actually accepting the text. But more experi- enced HyperCard users may prefer to be able to type blindly to enter ly . quick commands without having to show the Message Box. When tjrping blind, however, you had better be an accurate typlsL Since you can't see any mistakes you make, all you'll get is a beep and : an alert box from HyperCard if you make a slip of the digit. Fortunately, because whatever you type into a hidden Message Box stays In the box, you can see it by typing Command-M or choosing Message from the Go meim. , . ..^ , EixAHPLss: - . get the blindiyping . i . . set the blindTyping to false ' You Tkt It: Use a blarik Address stack card for this experiment. Make the Message Box visible, and type the following messages Into It: get the blindTyping . set the blindTyping to true . ' , ''W HyperCard Properties 485 hide msg put "howdy" into field 1 show msg set the blindiyping to false hide msg uh oh (Command-M) set the bllndTyping to it ^ ■ cursor Purpose: Controls which preset cursor displays on the screen during a script. When to Use It: You may change the shape of the cursor during the execution of a script by setting the cursor property to an existing cursor. The Macintosh system has four predefined cursors that you can call up by their internal id numbers. They are shown In Figure 28-1 . Perhaps the most Important one to note is the watch cursor. If you have designed an extensive script that causes the user to have to wait more than about one second, it would be a good idea to set the cursor to 4 prior to undertaking the rest of the lengthy script. Macintosh users are accustomed to waiting relatively patiently when the watch cursor is on the screen. If any other cursor is showing while a script is silently churning away, the user may feel that the program has "hung up" or Is unnecessarily slow In its execution. Surprisingly, the watch cursor ebmlnates many of those negative feelings. The cursor property always reverts to HyperCard's normal cursor settings when a script ends, that is, when HjrperCard starts sending Idle messages. This property is settable only. The Get command does not work with the cursor property. set the cursor to 1 set the cursor to 4 • t 2 3 4 Figure 28-1 . The four cursors installed in the Maetntosh System and their id numbers. 486 HyperCard's Programming Environment You Try It: Because the cursor properly returns to its regular Hyper- Card setting at idle time, it will be difficult but not impossible to see the four cursors available to you from the Macintosh system while typing a Set cursor command Into the Message Box. The trick is to type the message and hold down the Return key whUe the cursor quickly flashes between the Browse tool and the selected cursor. Try it now with the four cursor settings. dragSpeed Purpose: Controls the speed, In pixels per second, at which the Drag command operates. . ■ When to Use It: If your script uses the Drag command, principally to '-• ' ■ ;^ draw shapes on the screen with any of the palnttng tools, you can - ■ 'i control the speed at which the drawing occurs with the dragSped qr.: ;!t property. If you set the number to zero, the tool will drag at the fastest i : speed your Macintosh is capable of. Other settings, however, control '-' V the number of pixels per second at which the tool will traverse the screen. In certain instructional stacks, you may want to slow down dragging ■ so the user can see exactly how a drawing is made. A comfortable speed ■ ^ ' • to watch drawing is at around 1 50. At Idle time, the dragSpeed property ' ^ returns to zero. EXAMFI^: get the dragSpeed . set the dragSpeed to 185 ; -. j You Try It: Since the dragSpeed property returns to zero at idle tune, you'll have to place a script in a button to see how various settings affect the drag speed of a painting tool. Go to a blank card in the Address stack and create a new button. Enter the following script Into the button, and watch what happens when you click that button, on mouseup choose line tool set the hneSize to 2 set the dragSpeed to 25 drag from 320,175 to 320,75 set the dragSpeed to 100 drag from 340,175 to 340,75 set the dragSpeed to 200 " ■ ^ ' drag from 360,175 to 360,75 • r.. , v .■ HyperCard Properties 487 set the dragSpeed to 0 drag from 380,175 to 380,75 , ; ' choose browse tool ' -M'-" ' "■■ ^ •i; end mouseUp editBkgnd Purpose: Controls the edit domain. When to Use It: If your scripts perform any actions In a background- painting pictures, pasting buttons or fields- use the editBkgnd prop- erty to go to and from the background domain. Setting this property to true places you in the background editing mode, complete with hash marks on the menubar. As m the nonscrlpted world of HyperCard, if your script chooses the Browse tool, the editBkgnd property is set to false and the backgroimd editing mode is cancelled. Examples: .'^^mi.,! v- ^fo-n, . v • :3? v * <^ , get the editBkgnd : : • . , - ,<> set the editBkgnd to true You Try It: Type the following messages into the Message Box In any stack: get the editBkgnd -'i? it set the editBkgnd to true choose pencil tool ; ; f ' > choose button tool choose browse tool language •■'f!? ■ '.ins. 1 Purpose: Controls which language translator is In use When to Use It: Editions of HyperCard that have language translators built in can take advantage of this global property, which Is also set in the Preferences card of the Home Stack. This property controls the way the Script Editor translates the English scripts stored on disk to the user's native language. There is likely little need to change the language properly anyplace other than in the Preferences card. Still, you may wish to find out which language the user has his HyperCard set to in case your scripts address the user in multiple laiguages. 488 HyperCard's Programming Environnwnt get the language ., , i, . . set the language to German You Try It: If your edition of HyperCard does not have any language translators in it, you won't be able to try this property, other than to get the alert box that tells you no translator is installed for that languatif You can try it anyway. Type the following messages into the Message Box in any stack: get the language • • ^'v ■ t-' it set the language to Japanese set the language to it lockScreen .■. i .i.Av :'-- Purpose: Controls screen updating during script execution. When to Use It: Some message handlers need to go to various cards their way to retrieve information or find a specific card in another stack, All the screen activity associated with such motions may be distracting " ■ to the user. If you prefer to hide all the commotion from sight, you set the lockScreen property to true, prior to shifting around the sta This action essentially freezes and disconnects the screen from Hyper- Card. In the meantime, Hs^erCard can go ahead and perform anj; activity it would do normally, including putting information into Add cutting and pasting buttons, and drawing graphics In the background. HyperCard also records each card the script attends to in its card history (although not In Recent), even though you don't see the c^ pass before your eyes. By locking the screen, you also help speed execution of a script would otherwise be drawing many cards on the screen each time anew card appeared. You might still wish to set the cursor property to 4, s* that the watch cursor Indicates something is happening, when there Is no action on the screen. Even though the screen is locked, Message Box showing and hi J is still active. That means, however, that if the Message Box is hidd in the middle of a locked screen script, the Macintosh won't fill in the ■ blank space underneath the box. Therefore, carefully orchestrate the ■ ' showing and hiding of the Message Box to take place when the screen Is not locked. The lockScreen property reverts to false at idle time, so you ne set the property to false at the end of a script. You may, however, HyperCard Properties 489 to lock the screen during only part of a lengthy script. In that case, set lockScreen to false when you're ready for the user to see some action and the script still has more to do. Examples: ' ' '"i'--' " get the lockScreen ^ :. V V. .,, ■ set the lockScreen to true , . ./ ' ' You Try It: Because the lockScreen property returns to falseat idle time, you won't be able to test it from the Message Box. Go to the Address stack and create a card button on a blank card with the following script. Then click on the button and watch what happens and what doesn't happen. on mouseUp , . ., set the cursor to 4 ■ , set the lockScreen to true " r^.... . , . • > go next go Home go card "Stacks" end mouseup numberFormat . f. . , v Purpose: Controls the format of the displayed result of a math calcula- tion. When to Use It: Scripts often perform calculations on numbers. Currency or metric conversions, for instance, often require that highly disparate magnitudes of values be multiplied or divided. When such calculations are performed, their accuracy is heavily Influenced by the number of digits to the right of the decimal point to which the calculations are carried out. The greater the number of digits, the higher the accuracy. In math circles, this type of accuracy is called precision. Unlike a spreadsheet program, HyperCard stores numbers in its fields as straight text. If a number is stored as 3.96. that's all that HyperCard knows about the number, even if it was the result of a much more precise calculation that had several digits further to the right of the decimal. When the number was stored in the HyperCard field with two decimal digits, any further precision was lost. The numberFormat property establishes the precision (that is, the number of digits to the right of the decimal point} to which the result of any calculations in a script will be displayed or stored in a container. 490 HyperCard's Programming Environment After the script, at idle time, the numberFormat returns to the default setting of six digits to the right of the decimal. The parameter to the numberFormat property is a string with a sample of what the format should be, using three special charact the zero, the decimal, and the Crosshatch. When you specify a zero a location on either side of the decimal point, you tell HyperCard to display a zero in that location If no other number fills it. For example, the format "0.00" is the one you would use for dlsplajring dollars an cents, because you always want the one cent column to have a there. A calculated result of 7.6 would display as 7.60, Use the Crosshatch character when you are not concerned abou displaying zeros but want displayed precision to a certain number digits to the right of the decimal. Therefore, the format "O.****! displays the result with up to six digits to the right of the decimal always shows a zero in the ones column of a result. Since the format change takes effect only after the next arlthm operation, the script may have to perform a "dummy" operation, adding a zero, to apply the format to the number. If the new format shorter than the previous one, HjrperCard rounds the digits cut off the new format. E^CAHPLES: get the numberFormat set the numberFormat to "0.00" set the numberFormat to "0. ############" : . ' set the numberFormat to "00.00" You Tmr It: The numberFormat property returns to the default at idle time, so you'll have to experiment vrfth the help of a button - in a blank card of the Address stack. Enter the following script in a button: on mouseup set the numberFormat to "0.00" ^ , " put 1/8 into line 1 of field 1 " ; ' set the numberFormat to "0.000" . put 1/8 into line 2 of field 1 ' set the numberFormat to "0.00" ■ put "$" && 1/8 into line 3 of field 1 ; \" end mouseUp , ~ pOWerKeyS <:true or false> Purpose: Controls Power Keys setting. ault h a ers: o in a to pie, and ilglt »out srof t#r and etic like It is fby HyperCard Properties 491 WifflM TO Use It: Power Keys are the keyboard shortcuts available when you use the Painting tools. 'Oie powerKeys global property is the one that turns them on for you when you set the Preference card to do so. It is unlikely you'll need to adjust this setting In a script, but the stack script in the HyperCard Home stack sets it each time you start HyperCard. Examples: get the powerKeys ' ■ .. set the powerKeys to true ■ f ( You Tmr It: You may send a set powerKeys to false message from the Message Box if you like. Just to verify that this property does work. Then choose a painting tool, select a graphic element, and try one of the Paint menu items normally controlled by a Power Key. It won't work from the keyboard. We suggest you keep Power Keys turned on to help speed your painting work. userLevel <1 to 5> ting ript ;ard Powose: Controls the User Level for an entire HyperCard session. When to Use It: The five possible settings correspond to the levels listed in the Home Stack's Preferences card: si,, ,iw 1 Browsing 2 Typing 3 Painting 4 Authoring i 5 Scripting As you recall, each of these levels provides a fixed amount of access to modifying information In a stack or the stack itself. If you are distributing a stack whose access you wish to restrict, your openStack script wouW set the userLevel property to the one that Is most appropriate for that stack. If you do change the userLevel in a stack, it is your responsibility to get the previous userLevel {or fetch it from the Preferences card) and restore the property to its original setting upon closing the stack. You might want to get the property at the open, place the numbered setting in a global variable, and use that variable to restore the setting in a closeStack script. Examples: get the userLevel folv ' U;-.,' ■■: : v . 492 HyperCard's Programming Environment set the userLevel to 2 set the userLevel to priorLevel a global variable You TRY It: Type the following messages into the Message Box and check the menubar and menus after each to see how the setting changed the user access to the system, get the userLevel it set the userLevel to 1 set the userLevel to 2 choose pencil tool set the userLevel to 3 choose pencil tool choose browse tool set the userLevel to it - not at this levell -- OK now restore level Window Properties c M r > HyijerCard has three windows whose properties you may read and, tii some cases, change from a script. The windows are known as the Message Window (and its variants: Message Box, Message, or Just • Msg) , Tool Wimiow, and Pattern Window. You may get the location of the center of a window, the coordinates of the rectangle comprising a window, and the current vlslbihty of a window. loc[ation] Purpose:: Controls the top left comer point of a window. ■3 ' « When to Use It: You may get and set the location of any window on the ■i'-^ «5 screen, using the coordinate system of the Macintosh screen. Whenyou i^' ; get the location of a window, HyperCard returns (into It) the coordinates of the top left comer of the window's content region (just below the gity ? it . ■ u--'V'.- ^ ... ..^ show tool window ^ ^-j . >. , get the loc of tool window : . h ^ , s it . X, subtmct 25 from item 1 of it set the loc of tool window to it hide tool window rect[angle] Purpose: Reveals the top left and bottom right cooidlnates of a window. When to Use It: The rect property cannot be set, because the sizes of the three windows are fbced within HyperCard. You can. however, get their screen coordinates if it Is important for you to make sure they don't overlap each other or some graphical element on your screen when the windows appear. The rectangle coordinates returned by the get rect command (the coordinates go into It), are in the form le/i, top, right, bottom- four numbers separated by commas. You are free to perform calculations on any item in the coordinates. For example, if you determine that the bottom right comer of a wdndow will overlap a special graphics area on a card by 15 pixels in the horizontal plane, then you can subtract 15 from the first item in It, delete the last two items, and set the location of the window to It. Examples: ^ ,,, get the rect of Message Box n../ < r.- ai: : v : > get the rect of Tool Window i .U : . . : -n You Try It; Since this is a read-only parameter, the following experi- ment lets you fmd the current coordinates of the three windows. Type these messages into the Message Box in any stack: get the rect of Message get the rect of Tool Window , , . . »t ' • . ... ..r. get the rect of Pattern Window it 494 HyperCard's Programmtng Environment visible : v Purpose: Controls the visibility of a window. When to Use It: The visible property is more likely to be used with the Get command than the Set command, because it is quicker to type the shorter Hide and Show commands into a script. In practice, it will be more efficient for your script to simply hide or show a window regardless of its current visibility state. To test for whether a window's visible property is true or false wtU be a waste of HyperTalk's time. There Is no penalty for hiding a window that is already hidden. ExAHFiEs: ' get the visible of msg set the visible of tool window to true You Try It: Although it's a lot more typing than the Hide and Show commands, type the following visible property messeiges into the Message Box In any stack: ; get the visible of msg - v ; ■> ; t i r- :< it • set the visible of tool window to true set the visible of tool window to false set the visible of msg to false set the visible of msg to true ~ how good is your blind ^Ing? ' ■. i':':' , ■■ - • ' . ..:"!i;K. , '. - Painting Properties > - - v >i When your scripts Invoke the painting tools to draw graphics on caids, you will probably need access to various painting properties. These are the settings largely contained in the Options menu, which applies toal tools, and In the font dialog box, which applies to the te}tt too! only. Virtually everything you can set manually can also be set from a script, giving your scripts the ability to work as fully as a human operator could, brUSii Purpose: Controls the brush shape for the Paintbrush tool, When to Use It: Prior to dragging the brush from one point to another, you may wish to choose abrush shape other than the default round dot. HyperCard Properties 495 Setting this property to one of the thirty-two possible brush shapes Is the same as clicking on one of the shapes in the brush shape dialog box. In that dialog box are graphic representations of all brush shapes in a twelve-by-eight table. Each brush shape has a number assigned to it from 1 to 32. The numbering starts at the top left comer and works its way down the first column. The brush shape at the top of the second column from the left is number 5. Unless you change the brush shape, the default setting is shape number 8. Use the Set command to set the brush property to the desired shape. get the brush ■ ■ > i ' set the brush to 12 • ; set the brush to 8 : . ■ . ; ; ^ You Try It: To see the effect setting the brush properly has, you can leave the cursor anyplace on a card and type the following messages into the Message Box. Watch the cursor change with each command, choose brush tool set the brush to 1 i set the brush to 32 r j ; ; r-,, set the brush to 9 set the brush to 8 choose browse tool ''■''^ ■■<4 centered ' ' : filled - - ' • ' - ■ ^ ' ^i ^» Purpose: Controls the Options menu settings Draw Centered and Draw Filled. Whem to UflB It: Both the Draw Centered and Draw Filled commant^s apply to drawing shapes with the Rectangle, Round Rectangle, and Oval tools. Draw Filled also applies to the Curve, Regular Polygon, and Irregular Polygon tools. If your scripts are about to invoke any of these tools for drawing, consider whether you want the drawing to be from a centerpoint or filled with a pattern. Bear in mind that setting the filled property to true causes HyperCard to paint with the currently selected pattern. If you prefer a different pattern, then adjust the pattern property (see below). / 496 HyperCard's Programmir^ Environment Examples: ... , get the centered set the centered to true r get the filled / .. . . set the filled to false , ; - -s ; •. You Tht It: The simplest way to watch these properties react to the Get and Set commands is to select any paint tool and pull down the Options menu after each command to see how the check- mark setUngs in the menu are affected. When the property is set to true, the item is checked in the menu, even though it was turned on by command rather than by menu selection. Type the following messages into the Message Box and Inspect the Options menu after each command, choose rect tool get the centered • '*v v--- ' . It ^--'^ --'"^ set the centered to true ' ""^ " ' - ? ■ • get the centered It set the filled to true ■ ' .j,..*,^ Purpose: Controls the painting Grid. WinsN TO Use It: Turning on the Grid from a script may make sense If you're not sure that the coordinates you assign to the drag commands are completely accurate. With the Grid in force, the shapes will be drawn to the nearest 8-pixel square, assuring that shapes will be aligned to the invisible grid. When a script turns on the Grid, the Grid item in the Options menu is checked, just as if you had turned it on with a menu selection. Exahpi^: get the grid , . set the grid to false r" ' ; • You Try It: Pull down the Options menu after typing each of the following lines into the Message Box. Watch the check mark next to the Grid menu item. choose pencil tool set the grid to true set the grid to false HyperCard Properties 497 set the grid to true choose browse tool lineSize -.r - Purpose: Controls the thickness of lines painted by various tools. When to Use It: Prior to dragging any tool that leaves a line (except the slngle-plxeled Pencil), consider adjusting the lineSize property. This is the same as selecting from the line size dialog box. If you don't adjust the lineSize property, the default setting Is one pixel line thickness. Examples: get the lineSize ' ^ <, set the lineSize to 3 v You Try It: Because the cross-hair cursor for all tools that draw with lines of varying thicknesses adjusts itself to the thickness of the lineSize property, you may watch the cursor get fat and thin with the typing of the Message Box messages below, choose rect tool ' ■- -' • ' ' ■ • " set the lineSize to 2 ' ; . ; ^ set the ItneSlze to 3 ^ - ^ ^ set the lineSize to 8 . i . . - v get the lineSize • j ^ : f i^: it ■ : - ■ : ■ set the llneSlze to 1 i . ; ; choose browse tool ' ■ ; ''^ '- ^ multiple .u v Purpose: Controls the Draw Multiple menu option and the number of pixels between multiple images. Whew to Usk It: By setting the multiple property to true, you turn on the Draw Multiple Item in the Options menu. This setting applies to drawing shapes with tools like the Rectangle, Round Rectangle. Oval, and Regular Polygon tools. A script may also adjust the spacing between multiple drawings by setting the multiSpace property to a number from 1 to 9. The number represents the number of pixels between each of the multiple shapes left in the wake of the tool. 498 HyperCard's Programmtng Environment Examples: get the multiple set the multiple to true set the multiSpace to 5 • - ■ , ; ; '>r You Try It: Create a new card In the Address stack In which you can experiment with drawing multiple shapes. After each set multiSpace command below, drag the chosen paint tool to see the effects. choose round rect ' set the multiple to true ' = : . : - ■ '' set the multiSpace to 1 ■ • ' > set the multiSpace to 4 set the multiSpace to 8 : ; \ choose browse tool | P&ttem ' Pukpose: Controls the currently selected pattern. j When to Use It: Filling areas with patterns and drawing filled patterns are both possible from scripts. Before you can do either, however, you must set the desired pattern by way of the pattern property. ( Each of HyperCard's forty patterns has an Identifying number based ' on its location in the Patterns palette. This palette displays samples of : the patterns in four columns often patterns. Numbering starts with 1 I at the upper left comer and works its way down the leftmost column, ; The pattern at the top of the second column from the left is pattern j number 11. To fill an existing enclosed region from a script, first set the pattern. | Then choose the bucket tool and issue the click at command, specifying i a pixel coordinate someplace inside the enclosed region. ' get the pattern 'i' .-■^■■•^•^l>'■.!,■ set the pattern to 12 - ■' = You Try It: Type the following messages into the Message Box In any ; stack, and watch the pattern palette change with each setting of the •■. pattern property, set the visible of pattern window to true , , get the pattern ■ , ' ' it -.q,, .^ .- -'.h'..' -V. : set the pattern to 1 set the pattern to 25 HyperCard Properties 499 set the pattern to 40 hide pattern window polySides Purpose: Controls the number of sides drawn by the Polygon tool. Whbk to Uffl! It: The Regular Polygon tool lets the HyperCard author select from a palette of six standard polygons with 3. 4. 5. 6, 8. and infinite sides. Whatever number of sides is selected is stored in the polySides painting property. The minimum number of sides allowed Is 3. You can set polySides to 12 to make a dodecagon. The problem with polygons with too many sides, however, Is that the resolution of the Macintosh screen limits your ability to distinguish sides. After about fifteen sides, the objects look like circles. Just as you set the number of polygon sides before dragging a regular polygon tool, so too do you set the polySides property In a script before the Drag command. Examples: . i-,, ^.J, ,. get the polySides set the polySides to 8 You Try It: Type the following messages into the Message Box. After each Set polySides command, drag a polygon on a blank card to see how the number of sides looks. choose reg polygon tool a , ; get the polySides it set the set the set the set the choose polysides to 2 polysides to 12 polysides to 20 polysides to 5 browse tool — 3 is the minimum 1 ? teztAlign teztFont teztHeight textSize tertStyle * ■ .'Tw AjiJ'tA < bold I italic I underline I outline I shadow I condense I extend I plaln> Purpose: Controls font attributes of text painted with the Text tool. 500 HyperCard's Programming Environment When to Use: TTiese Ave properties all represent settings in the font dialog box you can adjust when typing text with the painting Text tool. This gives you full control over the way painted text appears when a script types it into a card or background graphics layer. Parameters to each of the properties should be self-explanatory In the list above, since the terms should be familiar to you by this point. When you set the textSize property, HyperCard automatically sets the textHeight (leading) property to approximately one- third again as large. If the default leading is acceptable, you won't have to adjust the textHeight property. The textStyle property may have any number of the parameters listed as possible styles. Simply list them as comma- separated parameters to the textStyle property. Examples: get the textHeight ., ■ m set the textFont to New York , ; ? -'-r set the textSize to 14 - ,. , , - set the textHeight to 16 ,, set the textAlign to center set the textStyle to condense, underline You Try It: Type the following messages into the Message Box in a blank card of any stack. After a Set message, t>pe a few words of paint text to see the results of the new setting. To type the next command, click the text insertion cursor inside the Message Box and press the Clear key to remove the previous message. choose text tool get the textFont it set the textFont to Chicago set the textAlign to right set the textStyle to underline, extend set the textFont to Geneva •' :> ■(<- set the textSize to 9 • set the textStyle to plain choose browse tool Stack, Background, and Card Properties There are only two properties that you can Inspect or adjust for stacta, backgrounds, or cards. The properties are the object's name and script, HyperCard Properties 501 name of Purpose: Controls the name of the object. When to Use It: You may read or change the name of any stack, background, or card object by summoning the name property for that object. In the case of retrieving the name of the current object, simply specify which object you want, as in get the name oj this background Following the convention of the Get command, HyperCard places the response in the It variable. When an object has a name assigned to it {all stacks automatically have names), the response includes the type of object and the object's name, the latter enclosed in quotation marks. Therefore, getting the name of the Home stack would leave stack "Home" in It. If an object does not have a name assigned to it, HyperCard leaves the type of object and Its id number In It. You may obtain a shortened or longer name for the object by specifying short or long before the name property, as In short name of bkgnd button ID 12. The short name gives only the object's name. The Home Stack's short name, for instance, is simply Home, without any quotation marks around it. The long name, on the other hand, gives you the position of the stack, background, or card in the HyperCard universe. A named card in a named background would return a long name property like this; card "Set Up Card" of stack "HD-20:HyperCard Stacks:My Stack" All named objects may have their name changed from a script by setting the name property to a new name. This also goes for stack files. Examples: get the name of this card set the short name of background to "Forms 1" ' ■ get the long name of stack You Try It: Type the following messages into the Message Box while at the Home Card: name of this stack '''' - '"- - .n . ..y short name of stack • " ' ■ ' i " H!. ; •• long name of stack ' ■' ■- ' • • ■ " ■ get the name of this background • - ..- v/. it . , set the name of background to "Home Background" . > name of background 502 HyperCard's Programming Environment naime of prev card <: ^ name of card 5 script of Pitrpqsb: Controls scripts from within a script. - ' When to Use It: A remarkable feature about H)fpeiTalk and the - ' ■ ' HyperCard structure is that scripts are self- modifiable. That means that scripts may open other scripts and make changes to them, A ' ' HyperCard author, therefore , may make some requests of the user the • ' first time the user opens the stack and insert those preferences Into " ' " scripts. The stack will be fully customized for the preferences of that user. A well-crafted HjrpeiTalk script might even be designed so that It learns its user's habits and adjusts its scripts accordingly. The . ^ potential for self-modifying scripts is enormous. Using the Get and Set commands with the script properties of stacks, ,j backgrounds, and cards (as well as buttons and fields, below), one ■ f . _ script can reach into another script and put any kind of text into that ... , script. The procedure would be to first put the script from the objectinto . , . . a variable. Make all necessary adjustments to the script, and then set ^ , the object's script to the contents of the variable. ^ ■ '" EXABIPLES: get the script of this stack set the script of card to empty ' You Try It: To experiment with getting and setting a script, first create a new card in the Address stack. Then open its Script Ekiltor and enter the following script: on mouseup beep 2 ' ■' ' ■ ' ■ - end mouseup Close the Script Editor and click once anywhere on the card [except - ,. in a text field). HyperCard should beep twice. Now type the following messages into the IMessage Box: get the script of card it -- you can see only the first line, but all three lines are in It, set the script of this card to empty Now click on the card. Since you emptied the script, the beep Instructions are no longer there. Type the next line into the Message Box: set the script of card to it HyperCard Properties 503 This restores the script to the beep script. Click once on the card to see for sure. Field Properties ,V , . - . \ Every field you create has fifteen properties that can be adjusted from a script. These properties will be familiar to you as the settings in the Field dialog box and the Font dialog box you can leach from It. 10C[atiOn] ■ ^^^nr^^n. I^jrpose: Controls the center point coordinates of a field. When to Use It: Unlike the location property of windows, the field loc property monitors the centerpoint of the field. By returning this location, you can make a script click in the center of the object with the Field tool to select the field. Then you can copy or cut the field into the Clipboard for later pasting on a different card or in a different stack. You have to be careful, however, when getting the location of the field to click the Browse tool as a means of setting the text insertion pointer flashing in a particular field for the user. If the field is a multiple-line field, the Click command wUl end up placing the text insertion pointer in a line other than the first line. In fact, that action will place return characters in every line above the insertion pointer (see the rect property for a way around this). • Examples: mj..- ; ■ •■ T i\>? ' get the location of field ID 4312 set loc of field 1 to 32, 145 ^ Tou Thy It: Go to the Address stack and create a new card field on any card in the stack with the New Field menu command. Adjust its attributes to be a rectangle style and check the Show Lines box. Choose the Browse tool, and enter some text into the field. Youll use this field for other experiments about field properties below. Now type the following messages into the Message Box: get loc of card field 1 it add 50 to Item 1 of it • . \ -^jr^ set the loc of card field 1 to it click at it '''' - -^'^ '-'^ 504 HyperCard's Programming Envtronment lOCkTezt . ShOWLineS ' .' user will ever use, except when user scripts create new fields. Examples: jl. !, , '. get lockText of card field 4 . set showLines of field 'Text 1" to false • , ,.1 set wideMarglns of field 3 to true .^ . ^ You Thy It: Using the sample card field from the last experiment, place the Browse tool atop the field and watch it change as you fype the following messages Into the Message Box. Also watch other attributes of the field and text inside the field change with the commands, set lockText of card field 1 to true ' set lockText of card field 1 to false • ■ " ' • set showLines of card field 1 to false set WideMarglns of card field 1 to true name " r . Purpose: Controls the name of the field. When to Use It: You may read or change the name of any field by summoning the name property for that field. Simply specify which field you want by field number or id, as in name ofjisld 4. If the field is a card HyperCard Properties 505 domain field, the domain name must be part of the field name (for example, card Jield "Names"). Following the convention of the Get command, HyperCard places the response in the It variable. When a field has a name assigned to it. the response includes the type of object and the object's name, the latter enclosed in quotation marks. Therefore, getting the name of a field called "Address" would leave n. ; field 'VWdrcss" • in It. If a field does not have a name assigned to it, HyperCard leaves "field" and its id number in It. You may obtain a shortened or longer name for a field by specifying short or long before the name property, as in get short name of field ID 12. The short name gives only the object's name. Hie short name of the above example field, for instance, is simply Home, without quotation marks. The long name, on the other hand, gives you the position of the field in the HyperCard universe. A named field in a named background would return a long name property like this: bkgnd field "Address ' of background "Rolo" of stack "HD-20: HyperCard Stacks:Addresses" A named field may have its name changed from a script by setting the name property to a new name. EXAMPLBS: get name of field I set name of card field ID 20 to "Special" . f m^-g put the name of field ID 9887 into field 2 You Thy It: Type the following messages into the Message Box whUe in the Address stack, name of field 1 name of field 3 set name of field 3 to "Say What?" ' " ' ' ' name of field 3 ■ set name field 3 to "Date" rect[angle] Purpose: Controls the size and location of a field. Wmem to Use It: Because every field maintains information about the coordinates of its upper left and bottom right comers, you can retrieve those properties or set them in a script. Notice that because the coordinates are those of the Macintosh screen, you can both resize and move a field by one setting of the rect property. 506 HyperCard's Programming Environment When you get the rect property, HyperCard places four coordinate numbers Into It. They represent the horizontal and vertical measures of the top left comer and the same for the bottom right comer. Each number Is separated from others by a comma. When you set coordi- nates for the rect property, the coordinates must be in this comma- separated format. Get the rect property of a multiple-lined field to find the location of the top left comer for choking the text pointer at the top of the field. The experiment below shows you how to manipulate the property Informa- tion in a variable to make the Click command work the way you expect BXAMFLBS: get rect of field "Entry" set rect of field ID 53819 to 34.150,134.250 YoD Try It: Use the card field from the previous experiments, and ^ the following messages into the Message Box: put the rect of card field 1 into myRect delete item 4 of myRect delete item 3 of myRect click at myRect set the rect of card field 1 to 20,20,100.300 script , _ ;> ; Purpose: Controls a field script from within a script. When to Use It: Using the Get and Set commands with the scrip! properties of fields, a script can reach into a field script and put any kind of text into that script. The procedure would be simOar to that outlined for modifying stack, background, or card scripts, above. Examples: get the script of field ID 43387 set script of field "Record Number" to empty set the script of this background to the script of this stack You Trt It: To experiment with getting and setting a script, go to the Home Stack and type the following messages into the Message Box: .M : . ,i , put "on mouseUp" & return into scriptMaker ,, . put "go next" & return after scriptMaker put "end mouseUp" after scriptMaker = o.; , set the script of field 1 to scriptMaker set the lockText of field 1 to true HyperCard. Properties 507 Click on the card's title field. That field now has a script In It that Instructs HyperCard to advance to the next card in the stack each time you click on the field. And that was done completely without opening the Script Editor to that field. Open the Script Editor to see the results of your handiwork. scroll - Purpose: Controls the number of pixels a scrolling field has scrolled from the top of the text, si - ' r or ; uf f^i-r'i :o Whek to Use It: Each time a card with a scrolling field in it appears on the screen, its natural tendency is to display its text starting with the first line. That may not be the desired effect for your card and stack design. By setting the scroll property of a scrolling field, you can automatically advance the text further down the block. The parameter to the Scroll property is the number of pixels from the very top of the text. If the position of scrolled text Is to be saved for each card for the next time it comes into view, retrieve the current Scroll amount and store the value in a hidden field In the course of a closeCard message handler. In an openCard handler should be a corresponding Set command to restore the previous scrolled location, BXAHFLBS: put the scroll of field "Description" into field "placeHolder ' set the scroll of field "Description" to 3 ♦ the textHeight-i of field "Description" You TkT It: Go to the Address stack card with the sample field you made at the start of the field properties section of this book. Enter several lines of text into the card field such that the text runs below the bottom of the field. Then type the following messages into the Message Box. set the rect of card field 1 to 100, 100,250.200 . , , ao- set the style of card field I to scrolling ,; put the scroll of card field 1 Into message , j, : ; , set scroll of card field 1 to 20 . , t , ; set scroll of card field 1 to 120 ;, ; c r Style < transparent I opaque I rectangle I shadow I scrolllng> Purpose: Controls the field style. ^ ■ . - i'l^ . ., ■ :! ■ Whek to Use It: Just as you manually adjust the style of a field in the Field Info dialog box, so can a script make the style adjustment by 508 HyperCard's Programming Environment setting the style property. Parameters to the style property are the same style names that you find in the dialog box. Scripts that generate new fields for a user would be likely candidates for setting this property. The new field procedure might start with a doMenu "New Field" command, which brings up the default, transparent style. If the new field is supposed to be a rectangle field, the style of that new button would be set to "rectangle." Examples: get style of field 3 ,r - r : set style of card field ID 4 to shadow «'.iy £f ;■ set style of field "ZIP" to transparent , ^ You Try It: Use the card field from previous experiments In the Addre^ stack, and watch the changes to the field after you each of the following messages into the Message Box, put the style of card field 1 into priorSetting set style of card field 1 to shadow set style of card field 1 to scrolling ' " set style of card field 1 to priorSetting textAlign teztFont textHeight teictSize textStyle , . , ■ <:r, /• . . i!r; < bold I italic I underline I outline I shadow I condense I extend I plain> Purposb: Controls font attributes of a field. When to Use: These five properties represent settings in the font dialog box you normally see by clicking the Font button in a Field Info dialog box. These properties give you full control over the way text appears In a field of your choice. Parameters to each of the properties should be self-explanatoiy inthe list above, since the terms should be familiar to you by this point. When you set the textSize property, HyperCard automatically sets the textHeight (leading) property to approximately one- third again as large, If the default leading is acceptable, you won't have to adjust the textHeight property. The textStyle property may have any number of the parameters listed as possible styles. Simply list them as comma separated parameters to the textStyle property. " ' HyperCard Properties 509 Examples: , get textHeight of field ID 9808 set textFont of field "Day 1 " to Chicago set textSIze of card field 2 to 1 0 set textHeight of field ID 12 12 to 12 , . , ■ <- . ? ' set textAlign of field ID 12 12 to right : set textStyle of field ID 1212 to outline . . i c Tou TkY It: Use the card field from the previous experiments and type the following messages in the Message Box. get textFont of card field 1 it ^.^ j-ifV set textFont of card field 1 to New York set textAlign of card field 1 to center set textStyle of card field 1 to bold set textFont of card field 1 to Geneva • ■ - '■^'"- ^'^ set textSlze of card field 1 to 9 set textStyle of card field 1 to extend, underline visible showName Purpose: Controls the highlight and name features of a button. When to Use It: If your scripts create new buttons for the user, youll want to make adjustments Just as you would from the Button Info dialog box. The Auto HUite and Show Name settings are check box settings in the Button Info dialog box. By setting these properties to true, the script does the same as checking these items. EXAMFI^: get autoHilite of button ID 43 ; , set showName of background button 1 to true You Tkt It: For all experiments In this section, create a card button In ■ any card of any stack you like. Use the New Button menu option to ' ' ' create the button, and leave the default settings the way they are. Now type the following messages into the Message Box. put the showName of button "New Button" Into msg set showName of button "New Button" to false set autoHilite of button "New Button" to true - click on the button now set showName of button "New Button" to true hUite 1 Purpose: Controls highlighting of a button. When to Use It: You'll get and set hilite property of a button most often when you're In the check box and radio button styles. As noted In the discussions about these button styles, the responsibility of making one HyperCard Properties 511 of a series of radio buttons the highlighted button lies with a script that responds to the mouseUp system message. The script must change all other radio buttons in the cluster to false highlighting, while setting the button just clicked to true highlighting. When a radio button is highlighted, It has a black dot in its center; when a check box is highlighted, it has an X in its box. You may wish to highlight other button styles, depending on the funcUon of the button and stack design. For example, if a card features a row of buttons, each of which links to a stack with a special funcUon, you may want that stack's button to be highlighted when you are in that particular stack. The extra visual feedback reinforces in the user's mind which of the special function stacks he is in. EXABIPLES: get hllite of bkgnd button 1 , : • , . • . set hilite of button "Choice 1" to true You Try It: Choose the button tool and double-click on the new button used In the previous experiment. Change the style to the radio button style and return to the Browse tool. Now type the following messages Into the Message Box to see how the hilite settings influence this style of button. set hilite of button "New Button" to true set hilite of button "New Button" to false - ■ Purpose: Controls which icon art is attached to a button. When to Use It: When a script creates a new button, it can assign an Icon graphic to the button and turn the button into an icon button all at once by setting up the icon property with a valid icon number or name. Just as in the Button Info dialog box the entry of an icon number both assigns the art and makes the button an icon button, so too does the icon property influence a button from a script. An icon setting of zero removes icon art from the button and terminates the button's designation as an icon button. If your script is changing a button to an icon button, chances are that the button will also have to be resized to accommodate the art. The default new button size is usually not tall enough to show the entire Icon graphic. Examples: get icon of button ID 40 512 HyperCard 's Progranmung Env ironment - set Icon of bkgnd button "Help" to 25002 .,: set icon of bkgnd button "Help" to "Med Help" You Try It: Since the new button you've been experimenting with will not be tall enough to accept icon art, select the button with the Button tool and adjust it so that it is approximately one inch square. Also open the button's dialog box to change the style to round rectangle. Then select the Browse tool and type the following messages into the Message Box. put the icon of button "New Button" into message . set style of button "New Button" to round rect set icon of button "New Button" to 1000 . set icon of button "New Button" to 14953 set icon of button "New Button" to "Mac" set icon of button "New Button" to 18814 loc[ation] Purpose: Controls the centerpoint coordinates of a button. When to Use It: Like the location property of fields, the button toe property monitors the centerpoint of a button. By returning this location, you can make a script click in the center of the object with the ; Button tool to select the button. Then you can copy or cut the button j into the Clipboard for later pasting on a different card or Ln a different j stack. Examples: get the loc of button "Cancel " set loc of field 1 to 200,150 You Try It: Type the following mouseUp handler into the Script Editor of the card button from previous button property experiments. Then click the button and watch what happens. get loc of button "New Button" add 30 to item 1 of it ; . set loc of button "New Button" to it • , : choose Button tool r- 'I click at it , doMenu "Copy Button" ' L ; go next card doMenu "Paste Button" go prev choose Browse tool - • ' ^ 4 HyperCard Properties 513 name Purpose: Controls the name of the button. - When to Use It: You may read or change the name of any button by summoning the name property for that button. Simply specify which button you want by button number or id, as in name of button ID 300, If the button Is a background domain button, the domain name must be part of the field name (for example, bkgnd button "OK"). Following the convention of the Get command, HyperCard places the response in the It variable. • . ^.i • " ' When a button has a name assigned to it, the response Includes the type of object and the object's name, the latter enclosed In quotation marks. Therefore, getting the name of a button called "Print Cards" would leave button "Print Cards" in It. If a button does not have a name assigned to it, HyperCard leaves "button" and its id number in It. You may obtain a shortened or longer name for the object by specifying short or long before the name property, as in get short name of bkgnd button ID 1 2. The short name gives only the object's name. "Hie short name of the above example, for Instance, is simply Print Cards, without any quotation marks around it. The long name, on the other hand, gives you the position of the button in the Hj^perCard universe. A named button In a named background would return a long name property like this: bkgnd button "Help" of background "Help Form" of stack "HD-20: HyperCard Stacks:Help" A named button may have its name changed from a script by setting the name property to a new name. Examples: ' ' ^ ■ / \r:":.\ ' get the name of button 3 ' , set name of bkgnd button to "Excel" get name of button ID 1 2 1 23 You TiiY It: Use the card button from previous experiments in this section and type the following messages Into the iVIessage Box. set name of button "New Button" to empty get name of card button 1 it set name of It to "Change" 514 HyperCard's Programming Enuironment rect[angle] Purpose: Controls the size and location of a button. When to Use It: Because every button stores information about the coordinates of its upper left and bottom right comers, you can retrieve those properties or set them in a script. Notice that because the coordinates are those of the Macintosh screen, you can both resize and move a button by one setting of the rect property. When you get the rect property, HyperCard places four coordinate numbers into It. They represent the horizontal and vertical measures of the top left comer and the same for the bottom right comer. Each number is separated from others by a comma. When you set coordi- nates for the rect property, the coordinates must be in this comina- separated format. Examples: get the rect of background button "Accept" set rect of button ID 802 to 15,300,65,330 You Tmr It: Use the card button from the previous experiments, and type the following messages into the Message Box: get rect of button 1 subtract 10 from item 1 of it add 10 to item 3 of it ■ f ; set rect of button 1 to It • i : > script Purpose: Controls a button script from within a script. When to Use It: Using the Get and Set commands with the script properties of buttons, a script can reach into a button script and put any kind of text Into that script. The procedure would be similar to that outlined for modifying field scripts, above. EXAMPI£S: get script of button id 23 set the script of button "Cancel" to empty HyperCard Properties 515 Tou Try It: Use the previous card button, and type the following messages into the Message Box: set script of button 1 to empty . ■ * put "on mouseUp" & return & "beep 3" & return & "end mouseUp" Into scrlptHolder , » set script of button 1 to scrlptHolder Click on the button. It should beep three times. Open the Script Editor to see the results of your handiwork. style < transparent I opaque I rectangle I shadow I roundRect I checkBox I radloButton > Purpose: Controls the button style. When to Use It: Just as you manually adjust the style of a button in the Button Info dialog box, so can a script make the style adjustment by setting the style property. Parameters to the style property are the same style names that you find In the dialog box. Scripts that generate new buttons for a user would be likely candidates for setting this property. The new button procedure might start with a doMenu "New Button" command, which brings up the default, round rectangle style. If the new button is supposed to be a radio button, the style of that new button would be set to "radio button." , . , ; : , get style of button ID 50989 ' '■' set the style of bkgnd button 4 to transparent ' ' ' set style of button "OK" to roundRect Tou Tut It: Use the card button from previous experiments and watch the changes to the button after you type each of the following messages into the Message Box. get the style of card button 1 :. , ;=• > ■< ■,' .. j?- it ■ ' ' ' ' " set style of button 1 to checkBox '\ set style of button 1 to radioButton . a ; ; r- set the style of button 1 to It ' ' ' ' 516 HyperCard's Programming Environment textAlign teztPont textHeight teztSize textStyle Purpose: Controls font attributes of a button's name. Wbbvt to Use It: Although the Button Info dialog box gives you no choice to change the font attributes of a button, you can modify them at will with these five text properties. The settings are the same as you normally find in a font dialog box. Parameters to each of the properties should be self-explanatoiyinthe list above, since the terms should be familiar to you by this point, When you set the textSize property, HyperCard automatically sets the textHeight property to approximately one-third again as large. Since button names can be only one line, however, the textHeight property Is not used. The textStyle property may have any number of the parame- ters listed as possible styles. Simply list them as comma-separated parameters to the textStyle property. BXAUPLBS: set textFont of button ID 3 to Chicago ' " " set textSize of button "OK" to 10 set textAlign of bkgnd button 3 to right set textStyle of button "Help" to italic, extend You Thy It: Use the card button from the previous experiments and type the following messages in the Message Box. set icon of button 1 to zero put the textTont of button 1 into message set textFont of button 1 to Geneva set textAlign of button 1 to right set textStyle of button 1 to outline, extend set textFont of button 1 to New York set textSize of button 1 to 9 ,,. set textStyle of button 1 to italic , ; ■- -i v>:'i • ;> > < bold 1 italic I underline I outline I shadow I condense I extend I plain> HyperCard Properties 517 visible Purpose: Controls the visibility of a button, Wh£n to Use It: The visible property is more likely to be used with the Get command than the Set command, because you can hide and show buttons with the shorter Hide and Show commands. In practice, It will be more efficient for your script to simply hide or show a button regardless of its current vlslbUlty state. To test for whether a button's visible property is true or false would be a waste of HyperTalk's time. There Is no penalty for hiding a button that Is already hidden. EXABIPLES: get visible of background button 2 set visible of bkgnd button "Itinerary" to true You Thy It: Although It's a lot more typing than the Hide and Show commands, type the following visible property messages Into the Message Box in the stack and button you used for the other experi- ments tn this section. When you're finished with the experiment, delete the card button, visible of button 1 set visible of button 1 to false . visible of button 1 show button 1 FYom properties, we now move onto HyperTalk's built-in functions. CHAPTER 29 Introduction to HyperTalk Functions In our discussions directed at HvPEf^TALK AUTHORS so FAR, THE TWO MAJOR AREAS we've been looking at are objects and commands. Commands are the first words In HyperTalk script lines. HyperTalk also contains many words in its vocabulary that let you retrieve information about Internal system workings, like the clock and the location of the cursor on the screen, plus information about text in containers. At the same time, HyperTalk lets you perform many math operations, which end up coining in very handy, even if you tend to shy away from math. Finally, HyperTalk provides a number of predefined constants— plain words that stand in for Important values your scripts need lirom time to time. The next six chapters focus on all these Items- elements that make up the balance of what most scripts require. About the only other knowledge you'll need to get rolling on HyperTalk scripts Is information on how HyperTalk makes decisions in your scripts. We cover that In chapter 37. For now, we'll demonstrate all the other parts of HyperTalk that All out your scripts. We'U divide the discussion into three broad categories: functions, operators, and constants. The format we'll use is the same as for commands and properties in the last several chapters, so you'll have a chance to experiment with each item when we explain it. ' ■ ■ ' : ■ . v' ' ■ I 'c-'r') !• ■ ' } :l ' '■" ! 519 520 HyperCard's Prograrnming Environment Functions The first point we must make about functions is how they difer from I^mmands At first glance, they may appear to be quite slinito sto you Sn type comm^ds and functions into the Message Box and • somemi^happen in either case. But In actuality, commands an LnctSSre7e?ydiffe^^^^ the way you incorporate them Into your scnpts. By and large, commands are orders directed at some h ing, Whdhe you ^e a command into the Message Box or put i^t into a scri^ commmid tells HyperCard to cany out some action. It may be putting soS^lrforSatlon^nto a field or locking the screen. When you Issue a CO—, it affects or changes the state of some -my-a cont^«. an object, a tool, a menu item, the screen, the system. The key word, ""^oron the other hand, does not provoke action. I^t.^^^^^ retrieves the current status of an entity and tells you wha tha sta^^ :^Shlng about that entity changes as the result °f P-^^^^^^^* the function, although it may change later or on Its own. For e:«imple se^errCerTalk functions look at the internal Macintosh clock to 11 v^r tHnS liir today's date or the current time laccordlng to the Sui^glofth^Uem^^^^ • se Sgs L at the instant it looks at the clock. The clock, o cour.^ coriSfues to tick away at its steady pace . If you want an update on the clock's status, you use the functioii again. The answer that a function produces for you is called Its resui ■ A^theTcommon way to express how a f-nc«on operat^^^^^^^^^ s^ t^ a funcUon returns a certain kind of value, like the date or the locator of^he cursor on the screen. Understanding how a function retums result Is of fundamental importance. Using Functions in Scripts The name of a function essentially acts as a substitute in pt Me for t^^type of information it returns. For instance, if you wish to di^ ■ astackXt automatically places the current ^"^^^^^^^^^^ :> the creation of a new card, the newCani message handler would m -'- like this: . . , r.^: V on NewCard '! ' ' ' put the date into field "Date" end NewCard Let's examine what happens in the command 1*--;^^ J^^I^^^ as you'll recall, requires two parameters: a source and a destination Introduction to HyperTalk Functions 52 1 container. The destination parameter you'll readily recognize as being a field, named "Date." According to HyperTalk syntax for this com- mand, the source parameter must be either a text string, an arithmetic expression, or the content of any container. The convenient property about the date function is that it returns a text string (in the form 3/4/88). A function's underlying mechanism lets us substitute the function name [the date) in the command line where we'd normally type in a text string. As HyperCard encounters the function name In the script, it practically says to itself, "OK, this is a function, so let's use its returned result as tihe parameter here." Whenever a command parameter calls for a text string, you can substitute a function. All HypeiTalk functions return text strings (although many results are entirely numbers). We repeat: All HypeiTalk functions return text strings that can be used as text parameters for HypeiTalk commands. All you do is plug In the function where the parameter belongs. HyperCard functions may be written In a script (or typed into the Message Box) in a couple ways, according to some simple rules based on the arguments following llie function name. An argument is like a parameter, and usually consists of a piece of information the function needs to calculate. If a function Is calculating the sine of 50, for example, the number 50 is an argument to the sine function; if a function calculates the average of five numbers, then the average function Is said to have five arguments. If a function requires one argument or no arguments, then the form may be either of two ways: 1) the function name preceded by the word "the"; or 2) the function name followed by the argument In parentheses. In the case of the latter, if there are no arguments, then you type a left and right parenthesis without any spaces or characters between them. Here are examples of valid functions the sin of 50 sin (50) , the date dateO When a function expects two or more arguments (or a variable number of arguments), then you may use only the parenthesis style, with arguments inside the parenthesis separated by commas. Here's what some of these functions look like max (10,30,40) average (3.6,12,9.8) In our discussions of functions in the next several chapters, we'll show the function name in the 'the" style wherever possible. This form Is more natural sounding in a script and is thus more true to the spirit ofHypeiTalk. ,r it r r ■ 522 HyperCard's Programming Environment in scripts, functions must not be surrounded by quotation marks If they are they are viewed as a text string consisting of the funcUon name. Therefore, if you were to issue the following command. put "the date" into field "Date" - HypeiTalk would put the words the date into the f stplug Ij. - ' function names as If they were a regular part of the HyperTalk language- because they are. r „„h™ can test the type of information that virtually any un U n returns by typing the function into the Message Box. Since the funcUon stn^TxSL for some internal Macintosh or HyperCard value^you - ■ "mpty type the function name (and the prefix "the" - wlthparento - around i£ arguments!, and HyperCard instanUy «hows you 1 s e^^^ ^ To show you all the HypeiTalk functions, we provide the fo lowing reference chapters. WeVe divided the functions Into five subject ar^^ . ^ time and date funcUons; keyboard and mouse functions, text func tions; math functions: and miscellaneous functions (including user- definable functlonsl. We strongly suggest you "^^fj^^'^'^Z^^^t every function, even if you won't necessarily use them all right away^ Sie more you are aware of the powers available to you. the more lik j vou are to think of ways to use them. In later chapters, we U apply most of these functions to real-world HyperCard applications. CHAPTER 30 Time and Date Functions ■ : ■■■"iO If you plan to use HyperCard to help organize your time, the HyperTalk time and date functions will become some of your most valuable program- ming aids. You'll have access to the Internal Macintosh clock and a few different formats for this Information. Typically, you'll also call upon the Convert command to perform additional time and date arithmetic. the date the abbreviated i abbrev I abbr date the long date - itd s ; h RETuimB: The current date, as maintained by the internal Macintosh clock. Whk* to Use It: Many stacks in a business environment will need some fonii of date stamping, often upon creation of a new card or when Information is updated on an existing card. Any one of the three date Junction formats should prove workable. The shortest of the three formats is the function, the date, which presents the date in a format like 8/6/87. One level higher in completeness is the abbr date, which has a format like Tliurs, Aug 6, 1987. At the high end is the long date function, which spells out everything, as In Thursday, August 6, 1987. The long date is the function to use if you need only the current day of the week or month in textual form. Rather than build long scripts that 523 524 HyperCard's Programming Environment painstakingly convert the numbers of the day of the week Into each day's text, simply extract the desired component from the long date's results. For example, if you need only the day of the week, use the long date function as a parameter to the command, as in ' ^ put first item of the long date Into field "Day of the Week" Similarly, for the month, extract only the first word of the second Item of the long date, as in put first word of Item 2 of the long date into field "Month" These two methodologies will prove to operate much faster than an)' other approach. Treat the results of these functions as straight text. You won't be able to perform any date arithmetic with these functions directly. Use the Convert command and its seconds or dateltems formats to perform date calculations. BXAUPLES: put the long date Into field 'Date" put the abbrev date into it open file the date You Thy It: Type the following functions and messages into the Message - Box from any stack: .• ■ \ J the date ' v , j - ' c i.J^,l•^ the abbr date ' ■ ■ s - :L ■-■^ : -r the long date . > . ■ ■ . ni first word of the long date Item 2 to 3 of the long date the time the long time Retukns: The current time as determined by the Macintosh clock Whbk to Use It: Both time functions wiU probably get a lot of use If the ■ ' • kinds of stacks you design involve managing time during the day. Time- 1» "> stamping the creation of a new card in a stack is a popular application, Your choice of function depends on the format you prefer. The time :':,;,■!— function presents time in the format 3:03 p.m. if you've selected 12-hour time in the Control Panel, 15:03 if you've selected 24-hour time, If you want the seconds to appear in the results, use the long time funcUon, tc - which returns in the formats 3:03:15 p.m. in 12-hour time or 15:03:15 in 24-hour time. Time and Date Functions 525 TVeat the results of these functions as straight text. You won't be able to perform any time arithmetic with these functions directly. Instead, convert the results of these functions to seconds or dateltems for calculation. Examples: > put the long time into field "Start Time" ' ask "Starting Time?" with the time You Try It: Type the following functions and messages into the Message Box from any stack: - — , , • the time the long time put "Experiment started at ' & the long time the seconds the sees ■•u Returns; Total number of seconds since 0:00:00, January 1, 1904, When to Use It: Use the seconds fiinetlon when you need an accurate counting of seconds within a HyperCard application. The internal Macintosh clock uses January 1, 1904 as the starting point of its time- and date-keeping. As a result, the number of seconds returned by this function is enormous— in the billions. Since the measure is from a constant starting point, you can compare the total elapsed time In seconds between any two points in the life of a HyperCard application, even when the computer Is turned offbetween sessions. Examples: " , put the seconds Into field "Hidden" subtract the sees from elapsedSecs : hs. i -- elapsedSecs is a local variable ; ; ■ w; ft; Tou Try It: Type the following functions and messages Into the Message Box from any stack: the seconds . • i . > . ; j ; • put the sees Into temp ' " ' ' ' - • . temp . .. ^ / -v. the sees - temp •• ;^ , ■■ . .. ? ^ the seconds / (365.25*24*60*60) - how many years since 1904 526 HyperCard's Programming Enuironment the ticks - ■^-.-^^^^-^^--'r -^ ■ -^^ ■ Returns: The number ofl/60thsecondsslncethelast system start-up, When to Use It: All the while the Macintosh is running, It keeps track not only of the ongoing time according to the clock, but also the number of tick intervals (1 tick = 1/60 of a second) since the machine was last turned on. In other words, each time you turn on your Macintosh, the system starts counting ticks from zero. When you turn off the machine, ' the tick counter stops, and the number of ticks is erased. In practice, the Macintosh sometimes misses a heartbeat as far as the tick counter goes. This may occur during disk drive access or during the flow of information through the serial ports. Therefore, the tick counter should not be deemed a reliable time counter over the length of atypical Macintosh work session. If you need accurate timings for long periods, use the other functions that take readings from the internal clock. The most practical application of the ticks function is to trap for a user's double-click. Since HyperCard itself does not have a double-click detector (that is, it sends only single mouseDown and mouseUp messages) , you can build a script that checks for how closely two mouseDown or mouseUp messages were sent by HyperCard. If the messages were sent very closely together— such as within twenty ticks , , of each other— the user issued a double-click. A sample script is shown . , " ■ " below (although It uses some decision- making that will be covered in chapter 37): . on mouseDown • , >r: ,'>,; global clicktick -- declare global variable , , ... i ;i, , ; put clicktick into temp -- retrieve previous click time put the ticks into clicktick put new click time in "■ - > -- global variable ,\ ^-j if (clicktick - temp) < 20 then beep 2 -- subtract and beep twice if close end mouseDown In the above script, we use a global variable, clicktick, to store the tick count of the most recent mouseDown message after the mouseDom message handler has ended. At the next mouseDown message, the script retrieves the previously stored tick count and places it into a local variable, temp. The last Hne of the script compares the two times by simple subtraction. If the two mouseDown messages occurred within nineteen ticks of each other (that is, less than twenty), then, in this simple example, the script Issues the Beep command. Place this script in a button and try it for yourself. See how far apart the two clicks of the mouse button need to be before the script no longer Time and Date Functions 527 considers it a double click. Increase the number if you want more distant clicks to be accepted as double-clicks. Note that since you are actually programming the double-click mechanism here, the Control Panel setting for the double-click distance does not affect what's going on here. That atfects only other applications and the desktop. put the ticks into counter divide field 3 by the ticks counter is a local variable You Try It: Type the following functions and messages into the Message Box from any stack: the ticks put the ticks into howMany howMany the ticks - howMany the ticks - howMany - see how quickly they tick! CHAPTER 31 Keyboard and Mouse Functions A SECOND IMPORTANT GROUP OF FUNCTIONS LETS YOUR SCRIPTS OBTAIN INFORMATION about the current status of the screen cursor and modifier keys (Shift, Option, and Command) on the keyboard. As with many of the functions! these functions end up being used as decision aids for a HyperTalk script. Although we haven't delved into decision-making yet, you'll get a gentle introduction to the basic concepts in this chapter as you see how decisions In scripts are based on the condition of keyboard modifier keys or the location of the cursor. tne mouseH , :n->a>' .: -v-n:.. ^ : :; the mOUSeV - -'■■qo? - ^n-^U'- r: ■^ ■• the mouseLoc ? ■ i^-^- ■ ■:-'^ '-^»;^fj-. -^-l Returns: Coordinate locations of the hot spot of the screen cursor When to Use It: The need for summoning the screen coordinates of the cursor may not seem obvious at first. But in many advanced HyperTalk programming situations, a well-crafted script can perform wonders with one button that might othervrise require dozens. For example, if a card features a list of To Do items, you might wish to add a column next to the items so you can check off each item when completed. One method to allow the user to check off an item with the mouse would be to put individual buttons over each check box. That, however, could add twenty or more buttons to the card. As an 529 530 HyperCard's Programming Environment altemaUve, you could create one large button over all the check boxes, Then use the script to retrieve the coordinates of the Browse tool when the user clicks the mouse (on mouseUp). Depending on the vertical — - coordinate along the column , the script could fill In the appropriate line <»nf v< with a check mark character. One button, one script. We'll show you how to do this when we modify the To Do stack started in chapter 17. Another application might call for the card to show a button or field when the user glides the cursor atop a specific spot or area on the screen. In this case, the card's script (or background script, more likely) would have an Idle message handler that continually reads the mouse location with the mouseLoc function. When the coordinates match those of the secret spot, the script shows the field or button. A HyperTalk author with the Pascal, C, or Assembly language experience could also design a different cursor style as a HyperCard resource. Whenever the user drags the cursor into the designated area, the cursor changes from the Browse tool to the new cursor. Commercial applications do it all the time. So, you see, there are several opportunities to use the mouse location functions. The three you have available let you obtain the vertical (the mouseV), horizontal (the mouseH), and both coordinates [the mouseLoc). When you request a single coordinate, the function return ' Just the one number. When requesting both coordinates, the mouseLoc function returns coordinates In the proper HypeiTalk format for multiple parameters— separated by commas— with the horizontal coordinate first. We mentioned above that the coordinate returned by the ftinctionsls where the cursor's hot spot is. One of the design parameters of am' cursor (C, Pascal, and Assembly language programmers get Involved with this, not HyperTalk programmers) is the pixel that represents the action point of the cursor. For example, when the arrow cursor is in the menubar, the hot spot is the very tip of the arrow. Ttiat is the pixel that must be In the menu title for you to pull down the menu. In the Bmm tool, the hot spot is the very point of the index finger (see Figure 31-1), That's where you should point to find the location of a screen object with the mouseLoc function. Examples: show button ID 200 at the mouseLoc If the mouseV > 120 and the mouseV < 140 then-i put "OK" into line 3 of field 2 show message at the mouseV + 25, the mouseH + 25 You Trt It: Type the following messages Into the Message Box from any stack. Move the mouse around and try the same messages to get a feel for the coordinate system of the HyperCard screen Keyboard and Mouse Functions 531 Browse Tool "Hot Spot" Figure 3 J -1. The browse tool's 'hot spot" is the reference point for HyperCard's mouse and mouseLoc Junctions. the mouaeV v r ' ^'-f- v - the mouseH the mouseLoc put the mouseLoc Into temp • show message at temp add 50 to Item 1 of temp ''-i/j.- , add 100 to item 2 of temp , , ' show message at temp the commandKey ' ' theoptionKey the shiftKey ... -..^(ux.-.u .oiq..,.^ Rbtuhns: Up or Down, depending on the state of the key at the time the function runs When to Use It: The Command, Option, and Shift keys are called modifier keys in Macintosh programming parlance. They get this name because, according to Apple's Macintosh User Interface Guidelines, you can modify an operation by holding down one of these keys whUe pressing any other key or the mouse button. We've seen how the Shift key modiiies the letters of the alphabet to capitals. Most of us have also experienced how the Command key alters the behavior of most keyboard keys when we wish to perform one of the keyboard menu 532 HyperCard's Programming Environment shortcuts programmed into applications like HyperCard. The com- mandKey, optionKey, and shiftKey functions give you the same power when programming in HypeiTalk. Hie primary way to use these functions is to test whether any of these keys is pressed when the mouse button is pressed (mouseDown) or released (mouseUp)— usually in a button script. Generally speaking, the button script will follow a specified path if none of these keys is pressed. If you want a certain button to perform double, triple, or quadruple duty— perform related but decidedly different operations when clicked— you can program the script to follow a different path, depending on which modifier key is pressed along with the mouse button. Here's what the skeletal structure of a quadruple-purpose button's script would look like: on mouseUp ^ , If commandKey is down then cany out the command-key version of this button exit mouseUp if optionKey is down then carry out the option-key version of this button exit mouseUp if shtflKey is down then cany out the shift-key version of this button exit mouseUp otherwise carry out the plain version of this button end mouseUp You don't have to set traps for each of the modifier keys in such a script. If you have only one alternate, say for the Option key, you wouH only test for the Option key. Even if the Command or Shift keys were held down, the script would JaU through to the plain version of the button, because the script Ignores the condition of the other two kevs, You can also trap for the simultaneous pressing of two modifier kejs, A script to do that for both the Shift and Command keys would look like • . ,, this (you can try It in a button script): on mouseUp if the shiftKey is down and the commandKey Is down " " then beep 4 ' * else beep 1 . end mouseUp If you hold down both modifier keys and click on the button, the scrl^ , , : ,■ will beep four times. With only one or no modifier keys held down, you'll get only one beep. All three functions return the text responses "up" or "down," which can be put into containers. This is good to know, because inalonj Keyboard and Mouse Functions 533 button script, you should place the test for a modifier key at the start of the script. If the test is later In the script, the user may remove his finger from the modifier key before the script gets to the modifier key function. For the function to return a "down" result, the modifier key must be down when the function acts. TTierefore, consider testing for the modifier key(s) first and placing the results of the test in a local variable that can be used later In the script, such as: , on mouseUp . r, ;-; put the optionKey into keyState . ■'■^[ — keyState is the local variable - ■ ' ^jS^ if keyState is down then-i carry out the option key modified version exit mouseUp end if " f ■■ . ■ carry out the regular version ''" . end mouseUp As you design your stacks and lay out the buttons on the cards, always look for possibilities of ganging up functions on fewer screen buttons. Too many buttons can make the screen look cluttered and confusing to the user. At the same time, however, make sure that the functions you apply to the same screen button are logically connected. For example, an unmodified click of a button may create a new card in a stack; a shift-click of the same button may delete the current card. And then, if there is a pattern to the modifier keys' actions to your buttons, maintain consistency throughout your environment. For instance. If you set an option- modified button In one stack to mean that the stack branches to a different background and searches text right away, then keep that system going throughout the environment you establish for your users. Examples: if the shiftKey is down then doMenu "Delete Card" ' put the commandKey into command — local variable v; if the optionKey is down then update -- "update" is a message handler r-. You Try It; Most of what we've been showing you about the modifier keys require incorporating the functions into decision-making scripts (see chapter 37). From the Message Box, however, you can see the effect of pressing the modifier keys on the functions. Type each of the messages below into the Message Box in any stack. Do each message 534 HyperCard's Programming Environment twice. The first time, don't hold down the designated modifier key when >■ pressing the Return key; the second time, keep the key pressed when you also press the Return key. You'll see that the modifier key must be .".j down while the function runs for the function to return the "down' 1,'= result. the optionKey ^ the shiftKey • '.^ ^ ' i ' • put OptionKey Into temp temp : ' u-.';-'; the mouse the mouseClick Returns: Up or Down for the mouse; true or false for the mouseClick. When to Use It: We'll talk about these two functions together, because they both relate to actions the user takes with the mouse button, In some cases, the two functions are Interchangeable (although the construction of the decision-making HyperTalk code differs slightly), but there is a distinct difference between the two. The mouse function should be used when an indication of the current ' state of the mouse button is required. If the mouse button is down at ' ' ■ the Instant Hj^erTalk executes the function, the function returns the text word "down." If the mouse button is up, the function returns ttie word "up." A fun example of this function is to write the following cari script: . ' >■-'. on mouseDown , ,4 repeat while the mouse is down " " ' ■ '[ 7^ " ' show message at the mouseloc end repeat end mouseDown This script starts when you press the mouse button on the card (not In a text field, however). As long as you keep the mouse button pressed, HyperCard draws the Message Box wherever the cursor is on tlie screen. The repeat construction (explained In chapter 37) keeps requesting the mouse function and executes the next line, provided the mouse function returns "down" as the result. The mouseClick function returns either "true" or "false." Oneoftiie best ways to use this function Is trap for the click of the mouse button, In other words, a script might keep repeating itself until the user elide the mouse button. You can try this by setting up the foUowlng message ^ • handler tn a card or background script: Keyboard and Mouse Functions 535 on beeper . - - . -sui a v ..< .*».4.„ _ repeat until the mouseClick ''' ' ^.t^-.i^o-^ vd >.i ; beep wait 5 end repeat . , ; - ■ ■ ■ : end beeper ^ v,,,. ^ - . Then type beeper Into the Message Box. This starts the script going. It will continue to repeat the beep and wait loop until the mouseClick function returns a true. A press of the mouse button will make that happen, thus ending the repeat and the message handler. Notice that the mouseClick function returns a true upon pressing the mouse button. It doesn't wait for the mouse button to be released. BXAHPLIES: See above. You Try It: Be sure to try the examples shown above. They demonstrate the dynamics of these two functions. Unfortunately, you can't experi- ment with these two functions from the Message Box except with the mouse button released. As long as the mouse button is down, you won't be able to send the message in the Message Box. Still, type the two functions into the Message Box to see how HyperCard responds with the mouse up. the mouse , ' . the mouseClick " the clickLoc ' • Returns: The screen coordinates of the last mouse click (at the cursor's hot spot), regardless of current cursor position When to Use It: Because it Is so easy to move the cursor on the screen, even accidentally after clicking the mouse, it's nice to know that HyperCard keeps track of the location of the last time you clicked. Especially if you need to use the mouse coordinates in an extended mouseup message handler, the cursor may have long moved from the original point by the time the script gets to the coordinate call (making the mouseLoc function useless). While you could save the mouseLoc coordinates at the beginning of the script, the cllckLoc function saves you from that step. As a rule, then, whenever you need to retrieve the screen location of a mouse click within a script, use cllckLoc instead of mouseLoc. The fast mousers in your user constituency wUl appreciate it. 536 HyperCard's Programming Environmerit Like the mouseLoc, the clickLoc returns screen coordinates sepa- rated by commas. The horizontal coordinate comes first. Examples: i-i"! if first item of the clickLoc < 30 then beep show field "Help" at clickLoc You Try It: One easy way to try this function is to click the mouse at the upper left comer of the screen and type the c/fcfcLocinto the Message Box. You should get the coordinates 0,0; Then move the mouse around the screen without choking the mouse button and type the clickLoc again into the Message Box. The location stays the same. Click the mouse button with the cursor somewhere near the middle-left edge of the screen. Then type the following messages into the Message Boxfrom any stack. put item 1 of the clickLoc into x put item 2 of the clickLoc into y add 300 to X > . ^ ^ add 20 toy ^ ' ' show message at the clicklxic show message at x.y ^ >, CHAPTER 32 Text Functions HyperTalk includes two types of text functions. One type lets you learn about the characteristic of text inside a container. The other type accommodates conversion between ASCII values and characters. This latter type is offered as a convenience to experienced programmers. Fortunately, even for them there Is little need to get "down and dirty" Into ASCII code, since HypeiTalk has simpler ways of handling the most- used control characters. All of these text functions have arguments attached to them. There- fore, for this section, we include a discussion about arguments for each function. the length of ^ l "^ Returns: The number of text characters In a container When to Use It: Whenever your script needs to know the total number of characters in a variable, text field, or other container, use the length function. It counts the total number of characters (that Is, Including Invisible return characters) In a container. The length function may be used to establish an endpoint for text analysis. You can also use it to validate the length of an entry into a small text field. For example, if you set up narrow text fields on a card form, you might want to limit the number of characters that a user can enter into the boxes. While the actual number that will fit varies with 537 538 HyperCard's Programming Environment the proportion of skinny-to-thick letters (most Macintosh fonts are proportionally spaced), you could select an average length that will fit comfortably in the box. Your script would be a handler triggered by the closeField message. In that message handler would be a section like the following: if the length of field "Name" > 25 then beep put "The name must be fewer than 25 characters" end if As with most other functions, you can place the results of the length function into a variable or other container and use it for further calculations in the script. Aroumbhts: The sole argument of the length fimction is the name of the container whose text it is to measure. Remember that a container may be any text field, local or global variable, the Message Box. the special local variable, It. or a selection. You can also substitute an actual teri string as the argument, but that wouldn't seem to make much sense in a HyperTalk script: If you already know the text, you certainly know its length and don't need a HyperTalk script to figure It for you. y,.. EZAHPLBS: y.n ^ put the length of field 3 into howLong — a local variable > I f If the length of title > 50 then beep — title is a local variable put the length of field 2/6 && "words" into message You Try It: For this experiment, it will help if you have access to acartl with different- length text strings. You can use the Address stack, create a blank card, and type one long string into field 1 , a shorter one tntofldi 2. Then type the following messages Into the Message Box; the length of field 1 the length of field 2 put the length of field 1 into temp put "Field 1 has " & temp / 6 & " words In it." into message offset (, ) V t Returns: The starting position of a text string within anothertext strtnj, When to Ubb It: Because the information that HyperCard stores In Iti fields and in Its object names is so dominated by text (despite HyperCard's heavily graphical environment) , It is important to havethe flexibility to perform a fuU array of analyses on the text. One of those analytical tools is the offset function. Text Functions 539 With this function, you can compare any piece of text (which may be a text string or the contents of a container] against the entire content of a container. The function returns a number corresponding to the number of the character at which the test string starts. Let's see how this works. If field 1 of a card contains the text "Crime and Punishment," you can try a couple of offset functions on it to see what it comes up with. If you were to type into the Message Box offset ("Crime", field 1) the result comes back as 1 , because "crime" starts at the first character of field 1. If you then type offset ("and", field 1) the result comes back 7, because "and" starts at the seventh character of the field's text. You can also test for the occurrence of single letters, nierefore, if you type offset ("1", field 1) the result is 3. The function stops at the first occurrence, so it won't find the second letter "i" in "punishment." Chances are that you will use the off"set function In the same script with one or more other text functions In your analyses. For example, if you wish your script to capitalize a word in a container, you would first find the starting location of that word with the offset function. Then you'd work with the characters one at a time and change from lower case to upper case with the charToNum and numToChar functions (below). You'd have to put the capital letter into the lower case letter in the container, so the offset function would help In giving you the starting character number, Argoments: Both arguments to the Off'set function may be straight text, but the more likely scenario will be for both to be containers. Hie first expression will probably be in a local variable, and the second expres- sion will be either in a field or another local variable. If you use a plain text string as either or both arguments, be sure each string is in quotation marks. Examples: ^^cxrx-u.^^: -^^r .^cuv^ . i ..^ put offset (field 5, field 1) into temp -- local variable put offset ("Boston", field "Cities") into It Too Try It: The Offset function is not one you're likely to use from the Message Box, but you can experiment with it just the same. By following the messages below, you'll put a text string Into a variable and then perform some offset functions about it. Type the following mes- sages Into the Message Box from any stack. 540 HyperCard's Programming Environment put "When in the course of human events..." Into It :.^'nn It ' offset ("course", It) •• put word 6 to 7 of it into temp temp '. u-:- offiset (temp, it) < m i/. ' i > » ; offset ("events", it) i offset ("events", temp) ■ ' • the niunber [of] tn Rbturnb: The number of components in a specified container ^, When to Use It: When performing analyses on text in a container, you usually need the maximum number of components before you can set up a repeating script structure (see chapter 37), Once you have the maixlmum number of words, for example, the repeating structure car < • i begin looking at word 1 , continue with word 2 , and so on, until the woni count equals that of the total number of words in the container. Hien : ; the repeating structure can stop. ■ . •- i .' Another application occurs frequently in multiple-lined fields. Ifyour ' " ' - script needs to add a new Item to a list in a field, it cannot predict how , It' > : many items will already be In the list when It makes its addition, Hk v:- -I script can use the number of lines function to find out how many lines c J are occupied with text. Then the script can put the new text In the ■ ■ maximum number of lines plus one. Here's how such a script would (' look: on mouseUp - i ; » £ ^ . , . answer "Any additions to the list?" , put number of lines in field "List" Into counter add 1 to counter , I , ! put it Into line counter of field "List" j' .j' , end mouseUp You'll discover that once you can retrieve the total number of teit components tn a container, you can gain quick access to specific parts of the text. (See chapter 34 for another version of the number function.) ,^ Arguments: Any valid component name works in the first argument , p This includes chars, words, lines, and items. J For the second argument, any valid container name is accepted, Meet of the time this argument will be a field (identifiable by field name, number, or id number) or a local variable. ■ ''' Text FuncUons 541 Examples: " put the number of lines of field 12 Into fleldLInes - local variable put the number of items of it Into howMany — local variable put the number of chars of first word of field 1 into it You Try It: Artificial though it may be, youll use the Message Box to experiment with the number function. Create a new card in the Address stack and type any kind of information into the first field, including text on many lines, and some series items separated by commas. Now type the following messages into the Message Box. the number of lines of field 1 the number of chars of field 1 • - . the number of words of field 1 the number of items of field 1 put the number of words of field 1 into theWords — "theWords" is a one-word local variable put the number of chars of field 1 Into theChars put "Field I's average word is " & theChars / theWords & " characters long." into message the charToNum of , the numXoChar of Returns; The chaiToNum returns the ASCII value; the numToChar returns the actual character , , i When to Use It: These two functions are direct opposites of each other. The charToNum function converts a keyboard character into its ASCII value; the numToChar function converts an ASCII value Into a charac- ter as it appears on the screen when typed from the keyboard. Both functions have ready application when it becomes necessary to work with characters that you cannot normally access from the keyboard- primarily control codes at the bottom end of the ASCII value table. Most of these codes are for use with printers and telecommiml- cations devices, although several of them find their way into standard files, such as the Tab and Return characters. Fortunately, for the common control codes. HyperCard provides constants In the form of plain words that we can plug in for those characters (see discussion about constants later in chapter 36). One special character you might be interested in is the apple character that appears at the top of the desk accessories menu. This character is not available from the keyboard in any fashion, but it is HyperCard's Programming Environment ASCII character 20 In the Chicago font. Hierefore, If you wanted to use this character in a text field set for the Chicago font, you'd have to send a message like this; put numToChar of 20 into field 2 Another application for these two functions is converting uppercase • to lowercase letters and vice versa. Since an uppercase letter and its lowercase counterpart have different ASCII values (separated by a value of exactly 32 across the entire alphabet), you can make conver- sions quite simple in a script. Here's an example of how a script would convert lowercase text in a field to all uppercase: on convert — message handler name repeat vrith x = I to the length of field 2 — repeat for each character put the chaiToNum of char x of field 2 into temp -- get ASCII value If temp >= 97 and temp <=122 then -- If it's in lowercase range , ." put temp - 32 Into temp -- put it in uppercase range put the numToChar of temp into char x of field 2 -- replace lower with upper end if . .':::v.. ■ . end repeat ;y ■ / end convert In this case, the two functions were used in tandem: once to convert the character to the ASCII vcilue for the arithmetic; the second time to convert the result back into the character for the text string. Try thb on a blank Address card. Place this script in the card's script, and type a mixture of uppercase and lowercase letters into the second field. Hien ^^e convert into the Message Box. Watch as each lowercase letter Is turned into its uppercase equivalent, ! Arguments: The argument for the chaiToNum function is any character you can type from the keyboard or any nonkeyboard character thatwas put into a container via the numToChar function at an earlier time, When the character is not one you can type from the keyboard, tt usually appears as a small rectangle. Because this argument can be any keyboard character you can use alternate characters, like the ones available by pressing the Option and Shift-Option keys. Choose Caps from the apple desk accessory menu and press the Option kp^to see some of the alternate characters. For the numToChar function, the argument Is any ASCII value froia 0 to 255. If you specify a number above 255, HyperCard autoroatlcallf Text Functions 543 subtracts 255 {or multiples of 255) so you have only one set of characters, the first 256 available largely from the keyboard. Examples: i.i put the numToChar of 27 before field 3 a , put the chaiToNum of "ae" Into temp You Thy It: The sample script above is a good experiment to tiy yourself. You may also do some conversions via the Message Box to help you get the feel of these two functions. Type the following messages into the Message Box from any stack. ' ' , - the numToChar of 167 the charToNum of "a" the charToNum of "b" the CharToNum of "B" put the charToNum of "A" Into temp add 32 to temp put the numToChar of temp into message CHAPTER 33 Math ■ Functions As YOU'W SEEN, YOU CAN GO PRETIY FAR WITH HyPERTaLK WITHOUT EVER GEnTING Into advanced math. In fact, you may not ever need the functions In this chapter. But for more experienced programmers or those who are comfortable with things like logarithms and compound interest, Hyper- Talk has many built-in functions to aid in those calculations. A few of the math functions require the full treatment that we give to functions In other chapters. A majority, however, are self-explanatory, and we'll treat them In a way that vrill help those familiar with the functions to use them quickly. We'U start with the more In-depth functions first. the random of ' " ' Returns: Random number between 1 and upper bound When to Use It; While business applications are not necessarily a likely target for a random number generator, many kinds of entertainment and education applications are. HyperTalk lets you request a random number between 1 and any number up to 32767. In an educational application, the random number may be used In Interactive math quizzes, so that not every problem is the same when the same user comes to the application repeatedly. In an entertainment program, the random number generator can mix up the pattern of the game to keep it fresh. i: v;- t s ' r ^ir 545 546 HypertJard's Programming Environment You don't have to use the random function when you wish the user to advance to a random card in a stack. For that task, the go to any card message is the desired route. ' ^ ■ ^ BXAMPIES: , , . put the random of 12 into field "Dice" If the random of 31 is 11 then-, put "This is your lucky day" into message If the minute Is the random of 60 then beep You Try It: First try typing the random of 100 Into the Message Box several times to get an idea of how random the random number generator really is. Then type the following handler into a new caid script In the Address stack. Then type dice into the Message Box, on dice repeat until the mouseCllck put "The roll is: "& the random of 6 && the random offi end repeat end dice the value of Returns: The calculated value of the arithmetic expression in a con- tainer When to Use It: Information is stored In a container strictly as tat information. That includes individual numbers and numbers linked together by operator signs like plus, minus, and so on. Therefore, if a container holds the text, 4*5, HyperCard sees it as a string of five characters: a 4, a space, an asterisk, a space, and a 5. There aretlmei however, when you need to know the calculated value of an expression like that when it is stored in a container. When a HyperTalk command calls for a container parameter, you usually plug In the name of the desired container, like ^eid 1 or jieldffl 890. Doing so is the same as writing the text of that container into the parameter. But if the parameter calls for a number, which happens to . ■ be the result of an arithmetic expression stored in a container, then use J. the value function to calculate that expression. Here's an example. On a card that resembles a scaled-down spreadsheet, there are twelve fields set up In a grid, as illustrated in Figure 33- 1 . Each field is named with its cell designation, like A 1 , B2, and so on. Near the bottom of the ; card is a place for you to type in the formula that will ultimately calculate the desired result of the numbers you type into various cells, So, you might type field "Al" + field "A2" + field "A3" Math Functions 547 A B C D 500 150 58 Formula | field "A1" field "A2" -t- field "AT] Answer [_ 668 1 113 put the value of fteld "Formula" into field "Answer" Figure 33-1. The text in the 'formulas" field needs to be evaluated to get the result Use the value fimction. into the formula field. That container now holds the text of the formula, but does not perform any of the arithmetic implied in the string. For that, you would have another cell, named "Answer," Into which the value of the formula field goes when you click the Calculate button. That button's script would be: on mouseUp .i-i. < .. , put the value of field "Formula" Into field "Answer" end mouseUp The value function performs whatever calculations are In the con- tainer specified in its argument and returns that answer. That answer, of course, becomes text again when It is placed into the desttnation container. Arguments: The sole argument for the value function must be a valid arithmetic expression, whether it Is entered directly Into the argument (for example, the value of " 12 / 5") or comes from a container. If there is text in the expression that cannot be resolved into a number (remember, a text string could represent a local or global variable holding a number), then an error message will result. EaEAHPLE: put the value of field "Formula" into it You Try It: The best way to experiment with the value function Is to place arithmetic expressions In a card's field and type the value of field X into the Message Box, where x is the number of the field. Notice that the Message Box is a special container in this regard, because if you type an arithmetic expression Into it, HyperCard automatically calcu- 548 HyperCard's Progranuning Environment lates the value of that container— hence the built-in calculator capabil- ity of HyperCard. SANE Functions The following functions will be familiar to experienced Macintosh programmers, because they are most of the math functions in the Standard Apple Numerics Environment, or SANE. The tntemal-num- ber crunching that these functions perform is actually buUt Into the Macintosh ROIVI and System. In describing the following functions, we elect to use the alternate format for designating functions— the function name and parentheses, Those HyperTalk programmers who are familiar with the purpose of these functions should feel comfortable with the format. Just the same, you may use the the function style for all functions that take fewer than two arguments, as in the cos of 40. abS (number) " ' - ? h Returns: The absolute value of the number parameter Example; ..v. . . abs (-23) returns 23 annuity (periodic rate, number of periods) Returns: The present value of one payment unit. Internally, this function performs the following calculations: 1 - (1 -H rl'""' annuity{r,n) = = To calculate the present value for the actual payments of an annuity, multiply the result of the annuity function times the amount of a single periodic pajmient. Example: annuity (0.1,12) returns 6.8137 'J' Math Functions 549 atan (angle in radians) Returns: The arctangent of an angle Example: atan (25) returns 1.5308 - average (number hst) -4 Returns: The average of the numbers presented In a comma- separated list Example: average (10,20,30) returns 20 compound (periodic rate, number of periods) Returns: Hie future value of a periodic payment unit. Internally, this function performs the following calculation: compound[r,n) = (1 + r)" To calculate the future value of an actual investment, multiply the results of the compound function by the periodic payment. Example: compoimd (0.1,12) returns 3.1384 COS [angle in radians) Returns: The cosine of an angle Example: cos (50) returns 0.965 (number) Returns: The natural (base-e) exponential Example; exp(4) returns 54.5982 550 HyperCard's Progranvning Environment eXpl (number) Retuhns: The natural exponential minus 1 . . ^| Exahflg: expl{4) returns 53.5982 , . - , eZp2 (number) Returns: The base-2 exponential . , ; , . Example: exp2(5) returns 32 . : In (number) , , Retuhns: The natural (base-e) logarithm of the number Example: ln(4) returns 1.3863 " ' ■ " ' ' Inl (number) '' " "V ' ^' ' Returns: The natural log of 1 plus the number, as In ln(l+x) Example: lnl(4) returns 1.6094 max (number list) . , Returns: TTie highest value in a comma-separated list of numbers Example: max(20. 50. 30.49) returns 50 min (number list) , Returns: The lowest value tn a comma-separated list of numbers Example: min(20, 50,30, 49) returns 20 round (number) Math Functions 551 Returns: The nearest whole number Example: round(12.5) returns 12, while round(12.51) returns 13. sin (angle in radians) Returns: The sine of the angle Example;: sin(75) returns -.3878 Sqrt (number) Returns: The square root of the number Example: sqrt(144) returns 12 tan (angle hi radiams) Returns: The tangent of the angle Example: tan(33) returns -75.313 ' tninC (number) Returns: The next lowest whole number of a number Example: trunc(4.825) returns 4 If you try these math functions and insert invalid numeric argu- ments, the function may return the error message "NaN," which means the result is "Not a Number." CHAPTER 34 Miscellaneous Functions I^ THIS CATCH-ALL CATEGORY ARE FUNCTIONS THAT PROVIDE INFORMATION ABOUT objects and messages. Most of these will be of interest to more advanced HypeiTalk programmers, but you should be aware of what these functions are. You never know when a function's capability will spark an Idea for a stack or operation in a stack. We also explore the powerful HyperTalk feature known as user-definable functions. the number of cards I buttons I fields Returns: The number of cards In the current stack; the number of buttons or fields in the current card. When to Use It: A common application that uses the total number of objects is when you need to set up a repeat loop to adjust each Item in the stack or card. The total number of objects is used as the maximum number of times the repeated procedure should be done. For example, let's say you wish to store Inlbrmation in one card that draws Information from field 1 of every card in a small stack. The task of the script would be to retrieve the text from each card's field 1. For the script to know how many times to do this, it uses the number of cards function to obtain a count of the cards. The script would look something like this: 553 554 HyperCard's Programming Environment on accumulate repeat with x = 1 to the number of cards put field 1 of card x after field "Summary" end repeat end accumulate v^^-> ^.-.jr- .-^ ,.— As you'll learn more In chapter 37, the repeat construction shown above Initializes the local variable, x, and assigns the value of 1 to it at the outset. In the next line of the script, HyperTalk recognl2«s the variable as a valid card number (the straight card number, not its m), The next time through the repeat construction, the local variable, x, is automatically incremented by 1 to a value of 2, and the Put command ViTorks on card 2. This repetition continues until x equals the value returned by the number of cards function. After that, the repeat cyde ends, and so does the handler in this case. Use the number of buttons and the number of fields functions carefully. If you don't specify a domain, the fields count will be background fields; the buttons count wiU be card buttons. To get the number of fields on a card, the function must read the number oj card fields. Background buttons are counted by the number of bkgndbuttoK (bkgnd and background are synonymous throughout HyperCard). If you want a grand total of both background and card layer objects, youH have to perform that arithmetic in the script, as follows: the number of background buttons + the number of card buttOBs Examples: put the number of background buttons into temp set name of card field id 20 to "Field " & the number of fields ^ if the number of cards > 100 then beep You Thy It: Use the Home card for this experiment, because it contains both background and card objects. Show the iVIessage Box and type the following messages into it, the number of cards .; , the number of fields '. the number of card fields ' the number of background fields , the number of buttons the number of card buttons the number of background buttons MtsceUaneous Functions 555 the result Returns: Indications that a Find or Go command failed When to Use It: HyperTalk provides a bit of what is commonly called error-trapping when a script attempts to find a string or go to a particular card and is unable to do so. Failure to find a match causes the function to return not found or invalid date, depending on the nature of the find string. Failure to find a card specified in a Go command causes the result function to return no such card. If the failure to accomplish the command affects the way your message handler proceeds, insert the result function immediately after a Find or Go command. As part of an if- then-else construction (chapter 37), the result function wiU let your handler take whatever action is necessary to make the handler run smoothly after a command failure. As peirt of a Find command, the result function might be used like this: on mouseUp find message ■ . • -y - ;•: i , ; if the result is not empty then ask "Sorry, I couldn't find that." with "OK" exit mouseUp i . end if . , . , . r, . - end mouseUp ,. The best way to handle the result function is to simply test for the presence of any string that the function might return. Since the function returns an empty string on a successful Find or Go, you can test whether the result is empty. If not, the message handler can branch to an error-handling script elsewhere, as in: if the result is not empty then doError Here, the error-handling message handler is called doError. EXAUPLES: See above. -ti- " !;^.f' -rwh" i>f; You Try It: Go to the Home Stack and type the following messages into the Message Box. the result ... ... ; . . ,,. ^ 556 HyperCard's Programming Environment find the seconds the result go card 20 — cancel the alert box the result ; , go card 2 : the result , ^ , ,. , , . the sound Returns: Done if no play command is active; the name of the sound resource playing. When to Use It: Whenever your script issues the Play command (see chapter 26), you can think of it as instantaneously sending all the note parameters to a separate section of the Macintosh to be carried out, ' • ' That means that as the music is playing, the script continues to mo^'e on to the next line. If you want the script to halt while the music plaw, your script should find out when the music is completed before proceeding. The sound function helps with that task. Used primarily in conjunction with "repeat" decision constructions (see chapter 37), the sound function returns the name of the Play command's voice parameter while the music is still playing. Once the music finishes, the function returns "done." A typical script construc- tion would look like this: on mouseUp ' * ;,, r . ^ - play end mouseUp Notice that the repeat section performs no other commands. It simply loops in circles between the repeat and end repeat lines until the sound function returns "done." Then the script breaks out of the loop and continues to carry out further commands. One reason you'd want to hold up further execution during a Play command's music is that some disk drives may Interfere with the tonal quality of the Play command's sound. A command after the Play command in the script may access the disk drive, A floppy disk or the original Apple HD-20 hard disk will cause momentary garbling of the sound when accessed during play. A SCSI hard disk should not interfere with the soimd. But if you don't know what kind of hanJwaie tiT V ' ! Miscellaneous Functions 557 the users of your stack may be using, play it safe by trapping for the sound function after a play command. Examples: , See Above. You Try It: If you type the sound into the Message Box, it will return "done" as long as no music is playing. To see the function return a voice name, go to the Play command's help card in the HyperCard Help stack (card ID 85099) . Show the Message Box and drag it so you'll have access to the sample sound buttons on the card. Before clicking a button, type the sound into the Message Box. Now click a button and press Return to test the function. The name of the voice wiU appear in the Message Box. Retukns: TTie id number of the object receiving the last message sent up the HjrperCard hierarchy When to Use It: Since this function lets you discover who the original target of the current message is, your script could use this information to send a different message. For example, you might set up a card in your Home Stack with several icon buttons representing stacks you've designed. If you name the buttons with the stack names, you only need one message handler— in the card object— to link those buttons to their respective stacks. The card handler would read: on mouseup ' get short name of the target r : . j-x ; go It : ■■ f/ i. • end mouseup The first command puts the button's short name— the same as the desired stack name— into it, because the button became the target when you clicked it. Then the Go command uses the button's name as Its parameter. You can keep adding new stacks' buttons to this card without ever writing another linking script between a new button and its stack. Examples: send "mouseUp" to the target get the nataie of the target ' ; v;, ; i You Try It: If you try typing the target tnto the Message Box, it wUl always return the current card's id number, because that's where the the target 558 HyperCard's Progranvning Environment Message Box sends all its messages. To see a different result from this function, create a new button in a stack and enter the following script into it: on mouseup put the target into message end mouseup When you click on the button, the button id will appear in the Message Box. . ,, . , ,,. . the psuram of ; »• * the paramcount the params iv ^ i . Returns: Hie text of parameter specified by ; the number of parameters; and the complete list of parameters to the current message, respectively. When to Use It: These three functions can contribute a substantial amount of power to your scripts, because they allow you to retiievt ' parameters that you send with your scripts. This requires a bit of explanation. Most of the message handlers described so far in this book have been those that trap for system messages that HyperCard sends to various objects in the hierarchy— things like mouseUp, openCard, and so on, But there is an entirely different class of messages: messages that your scripts send to other message handlers that carry out tasks you design. Experienced programmers caE these other message handlers subm- tines. Let's say that you have designed a card with five fields in it. Lets also say that you want all text In each field to be all uppercase. In case the user forgets to type In uppercase, you plan to include a script In each field that will convert lowercase letters to uppercase letters automatl- : cally when the user advances to the next field (that is, on closeFleld). As we saw in our explanation of the charToNum and the numToChar functions, the conversion routine takes several lines of HypefTalk instructions. While you could write the complete conversion routine In each field's script, there is a shortcut: Put the conversion routine in a stack or background script, and let the field scripts branch to the singls conversion routine whenever they need it. Such a background script might trap for the message toUpper. Its message handler, then, would begin witii on toUpper and finish up ulth end toUpper, as shown below: Misceikmeous Functions 559 on toUpper repeat with x = 1 to the length of field 3 ' " ' ■ get the chaiToNum of char x of field 3 ' ■ '' ' if it >= 97 and it <=122 then ' • subtract 32 from it '- ■ put the numToChar of it into char x of field 3 end if end repeat ■ ■f'-' >-■''■, end toUpper . ■ -! i , .: ■ , - • .rria;; Since the field script is located in an object very low in the hierarchy, its toUpper message would first go to its own object and then work its way up the hierarchy until the background message handler, on toUpper, traps it. When the conversion is completed, the original script in the field object continues on. But there is a special problem with this kind of subroutine. The toUpper message handler needs to know which field it should convert. You solve that by sending a field number, id, or name as a parameter along with the convert message, as in toUpper 3 for converting field 3. Inside the toUpper message handler, then, you can retrieve the parameter with the help of one of these three functions and Insert the number in the appropriate parts of the convert script, as shown below: on toUpper • put the param of 1 Into whichFleld ' repeat with x = 1 to the length of field whichField get the charToNum of char x of field whichField if it >= 97 and It <=122 then subtract 32 from it put the numToChar of it into char x of field whichField end repeat ■ , a . li ?^ c/o) end toUpper In the script for field number 3, then, would be the following message handler: oncloseField ; , , ., , ., . : . toUpper 3 . -.^.^ii .^^ : j . -.J": end closeField The number 3 wUl be used by the toUpper message handler as the number of the field to convert to uppercase. These three functions, then, give your scripts access to parameters that are sent along with messages. Here's how they differ. 560 HyperCard's Programming Environment The param function lets you extract a known parameter from the list In the above example, only one parameter was sent along with the message, but that's not always the case. For example, if you send parameters specifying the location of an object on the screen, there will be two parameters in the message, separated by commas, {such as, (50,75)) . By specifying a parameter number In the function's parameter (In the ), your script can pick out a single parameter and act on it, if necessary. The param of 0 is the message name; the param of 1 is the first parameter of the message; and so on. If your script needs the entire message, complete with parameters, •• ' then the params function (notice the "s" on params) returns the entire message. By putting the complete message into a container, like a ' variable, you can then dissect the parts as needed. Lastly, to help in extracting multiple parameters from a series of many parameters, you can use the paramcount function to determine the total number of parameters in the message. As with most other functions that return the total number of something, the paramcount function will most often find itself at home as a counter within a repeat construction {see chapter 37) . ' • : Examples: ' put the params into fuUMessage -- a local variable show message at the param of 1 ,the param of 2 add 100 to item the paramcount -1 of fuUMessage You Tmr It: Working with these functions from the Message Box wont be too helpful in your understanding of these functions. It's more important that you try the toUpper message handler shown above and understand its workings. Since menu commands send some parameters, you can try a short card script that displays the results of each parameter function In a field on a blank Address stack card. Type the following script Intoa blank card's Script Editor. Then choose menu items like Message, Find..., or desk accessories, which don't move you from the card, Compare the values of each function type. on doMenu put empty into field 1 put "The paramCount function returns "-i i & the paramCount into line 1 of field 1 '•■ - put "The params function returns "-1 & the params into line 2 of field 1 repeat with 1 = 0 to the paramCount put "Param " & 1 & " is "-, & param(i) into line 1+3 of field 1 Miscellaneous Functions 561 end repeat pass doMenu end doMenu User-Defined Functions You aren't restricted to HyperCard's built-in functions. You may create your own to perform any frequently used calculations In your work. User-defined functions, just like HypeiTalk functions, return values and may be used like any HyperTalk function in your message handlers. To define a function, you type it into an object script in the following form: function [ parameter ] return end Here's a sample function you might find useful in your stacks: function dayOfWeek date get date convert it to long date return item 1 of it end dayOfWeek To use this function, type dayOJWeek("ll/ 12/87") into the Message Box. You could also say put dayOJWeek(the date) intojield 1 , Just like any valid function. Note that user-defined functions must be called with the parenthesis form, not the "the" form. Here is another function you can use to calculate factorials of numbers (for example, factorial 5 = 5*4*3*2* 1): function factorial n if n <= 2 then return n else return n * factorial (n-1) end factorial This example serves double duty, because it demonstrates not only a function definition's basic structure, but also a doubling back on itself (recursion) by calling itself. If you create or discover functions that might apply to many stacks, you'll be best off to place the scripts for those functions in your Home Stack. Since function calls follow the same hierarchy through the 562 HyperCard's Programming Environment HyperCard system that messages do, you'll want the functions to be In a place accessible to all stacks. As you develop functions that other people might find useful, dont keep them a secret. Spread them around through user groups. There will surely grow large libraries of public domain HyperCard functions we can all use and learn from. CHAPTER 35 Mathematic Operators If there is one part of computer programming that usually FRIGirrENS newcomers, it's math. We hope, however, that you've seen how much you can accomplish without getting deeply Into mathematics. In fact, most HyperTalk programming requires little more than a basic working knowledge of arithmetic. In this section, we explain each of the operators you use in HypeiTalk scripts to perform math and mathe- matical comparisons (for example, whether one value is greater than another). These operators behave very much like functions . They return values, either the result of the actual math performed or a true/false determi- nation. Like a function, the result may then be placed into a container. You'll see many examples of what we mean in the following operator descriptions. (plus) . Returns: The sum of two numeric values Whew to Use It: The plus operator lets you sum two numbers together in an arithmetic expression. You can add two straight numbers, any container that evaluates to a number, any function that returns a number, or any combinations thereof. 563 564 HyperCard's Progranvning Environment Examples: put Item 3 of the long date + 2 into field "Future" show message at param I + 25,param 2 + 25 put field 1 + field 2 + field 3 + field 4 into field 'Total" You Try It: Type the following messages into the Message Box from any stack: put 10 into tempi put 500 into temp2 tempi + 1 tempi - the container doesn't change put tempi + 1 into tempi tempi -- now it changes tempi + temp2 add tempi to temp2 temp 1 temp2 add temp 1 + temp 1 to temp2 temp2 (minus) . ' Returns: The difference between two numeric values When to Use It: The minus operator lets you subtract two numbers In an arithmetic expression. You can subtract two straight numbers, any container that evaluates to a number, any function that returns a number, or any combinations thereof. Examples: put item 3 of the long date - 1 into field "Last Year" put "almost" after the number of words - 1 In field id 0770 You Try It: Type the following messages into the Message Box In any stack: put 500 into big put 5 Into small big - smaU small - big ' ■. ■ -j j subtract small from big ~ big . u - Mathematic Operators 565 small add small - 5 to big big small - 5 (multiply) 4V' • Returns: The product of two numeric values . * ] When to Use It: The multiply operator (the asterisk character, Shlft-8) lets you multiply two numbers together in an arithmetic expression. You can multiply two straight numbers, any container that evaluates to a number, any function that returns a number, or any combinations thereof. put field "Monthly Rate" * 12 into field "Annual Rate" p ' put 2 * 2 * 2 into field "Two Cubed" You Try It: Type the following messages into the Message Box In any stack: put 10 into X put 5 into y ■ - h • i » , • x*y ;■- .'V, . ■ put X * y into it add y + y to y y multiply X by y X y . (divide) RETURira: The quotient of two numeric values ' " When to Use It: The divide operator lets you divide two numbers in an arithmetic expression. You can divide two straight numbers, any container that evaluates to a number, any function that returns a number, or any combinations thereof. 566 HyperCard's Programming Environment Examples: put field 'Total Year" / 365 into field "Per Day" put X / y into z - three local variables You Tmr It: Type the following messages into the Message Box in any stack; put 100 Into big put 5 Into small big / small small / big . • • put big / small into it : * v :.yv put small & " is If" & big / small & "th of" & big ■ (equals) O (isnotequaU ' - S ' is not Returns: True or False, based on an arithmetic comparison of two expressions or containers , When to Use It: The equals and is operators may be used tnterchangea- bly. When comparing two expressions or containers placed on either side of the operator, HjrperCard evaluates whether the two items havs the same value. If so, the operator returns true. If not, the operatot returns false. The other three operators, also interchangeable with each other, test for whether the items on either side are not equal. If they evaluate to diff'erent numbers, the operator returns true. If the items are the sajne, then the operator returns false. To type the first of these operators, tj-pe the less than symbol {<) followed immediately by the greater than symbol (>) without any space in between. For the second "does n»t equal" symbol, a common math symbol, hold down the Option key and press the equals key. The "not equals" character appears In most fonts, but not all. Even if the symbol doesn't appcEir, the character's number is duly logged, so you don't have to see it to use it. The symbol does appear, fortunately, in the font used for HjrpeiTalk scripts, so fed free to use it there. Mathenmtic Operators 567 EXABIPLES: if field 1 = field 2 then-- ask "Should both fields be the same?" with "Yes" or "No" if X / 0 then put 0 Into x repeat while the hour is 9 . . , . if field 'Year" <> the year then beep 2 You Try It: Type the following messages into the Message Box irom any stack: put 100 into tempi put 100 into temp2 put 99 into temp3 temp 1 = temp2 tempi is temp2 tempi <> temp2 temp 1 / temp2 Oess than) (less than or equal to) (less than or equal to) (greater than) (greater than or equal to) (greater than or equal to) Returns: Tine or False, based on an arithmetic comparison of two expressions, containers, functions, or any combinations thereof. When to Use It: These four operators let you test for greater precision of a comparison than Just whether two numbers are or are not equal to each other. They let you test for a value being in a range, like whether a number is less than 10 or greater than 100, The addition of the equal sign helps you in the definition of the limit of the range. This is especially helpful when the limit is deiined by a function, whose value you never know beforehand. If you want to know if a variable is less than or equal to the current minute (as derived from a dateltems conversion), you can do that. If the current minute should not be in the limit, then use the simple less than operator. (To define both an upper and lower limit to a range, see the and operator). To type the special single character sjrmbols for less than, greater than, or equal to, type Option-Comma and Option- Period, respectively. These symbols may be more familiar to you from your math training. 568 HyperCard's Progranuning Environment Almost every application of these operators will be in repeat and decision making constructions, as detailed in Chapter 37. Examples: ' ... , if field 3 < 0 then put 0 Into field 3 • . . r; repeat while item 5 of field "Time" <= 5 If item 3 of the long date > 2000 then-i put "Reset your clock" into message You Try It: Type the following messages into the Message Box In any put 100 into tempi put 100 into temp2 put 50 into temp3 temp 1 <= temp2 temp2 <= tempi temp3 >= tempi temp3 <= temp 1 temp 1 + temp3 >= temp 1*2 Returns: Div returns the whole number of times one number is dMsible by a second; Mod returns the remainder left after dividing one number by a second. When to Use It: These two functions come in much handier than you might think at first (that is, unless you're a seasoned programmer and already appreciate their importance) . When you divide one number by another, there is a good chance that the result will not be a whole number, but usually a number and a decimal, like 5 / 2 = 2.5. But in the way we learned division in the second grade, the problem re'solves to an answer of 2 with a remainder of 1 (see Figure 35-1), These div and mod functions let you isolate the whole number and the remainder of a division problem. If we take a new problem and apply each of the functions to it, youl see the distinction between the two. The problem is that we at reviewing a project schedule that extends over a fixed number of daj-s, 98. We also know that the project schedule started counting on a Sunday sometime back. What we want to knowfirst is how many weeks stack: div mod (divide and truncate) (modulo) Mathenvatic Operators 569 2 -A - '^'^ Figure 35-1. Division the way we learned it in grade school. ■. . t the 98 days account for. For that answer, we use the dlv operator. Solving for 100 div 7, the answer comes to 14. In one operator, we both divide 100 by 7 and strip away the decimal part of the answer, since we're only interested in knowing the total number of weeks. Of course, this response tells us only the number of full, seven -day weeks. We don't know If there were any extra days into the eighth week. That's what the mod operator finds for us. By solving for 100 mod 7, the answer comes to 2. If we had simply divided 100 by 7, the answer would have been 14.2857 weeks. How many days is 0.2857 weeks? The mod operator tells us that it is exactly 2. So the project took 14 weeks and 2 days. Not only that, since we know the project started on a Sunday (day 1 of the first week), the project ended on a Monday (day 2 of the 15th week). Examples: put "$" & (amt div 1) & "." & (amt*100 mod 100) into money if it mod 2 is zero then put 'Even" into field 2 You Try It: Type the following messages into the Message Box in any stack: >irf-^-- kh^- V,v}<^^'^'-i' u;^:'' put 100 Into tempi , • , ■ . ^ ,r.. put 103 Into temp2 - % . > ' ■ - ■ . • ■ - tempi div 5 ■• > jr : ; i;, ^ temp2 div 5 ■ ■. r . .:; templ mod 5 : = ■ :r;. : •»■;,;,:■- : i; - > temp2 mod 5 ^- •: : > - - - Nm temp2 div 5 & " with a remainder of " & temp2 mod 5 50 div -10 50mod -10 • ..... 570 HyperCard's Programming Environrrvent Miscellaneous Operators The remaining operators are a mixed bag of logical, text, and comniand operators. and or not Returns: And and Or return True or False depending on the relationship between two comparison expressions; Not returns the opposite of the logical result of a comparison expression. When to Use It: All three of these expressions are used primarily in repeat and decision-making constructions (see chapter 37). They are sometimes called Boolean operators, because they're based on Boolean ■ algebra, a math system founded by George Boole in the nineteenth century. The And operator lets you establish two comparison criteria, both of ; which must be true for the operator to return true. If one of the comparisons is false, then the operator returns false. In other words, ' condition A must be true and condition B must be true for the whole statement to be true. > J You have a few Important ways to apply this tool. For example, you can specify a range of numbers within which a comparison figure must be before a certain procedure is carried out. If you want the script to beep when a number in a field is between 10 and 20, the conditional test would look like this: if field 1 >= 10 and field 1 <= 20 then beep Notice that on either side of the And operator is a complete compari- son statement. Including the field number and the math range, Botli sides must be complete statements, as shown. You cannot use ifjleld 1 >= 10 and <= 20 then beep. The script doesn't remember the field I part for the second comparison. If you change the direction of the less than and greater than signs in the above conditional construction, you can test for a number that is outside the range of 10 to 20, as follows: if field 1 < 10 and field 1 > 20 then beep Indicating that the number is out of the desired range. You may also test for two completely different conditions, both ! which must be met for the operator to return a true. For instance, you may insist that one field have a number greater than 1 00 while a second Mathematic Operators 571 field has specific text In it. Such a test would look like this if field 1 > 100 and field 2 is "Pounds" then... In other words, any two comparisons may be used on either aide of an And operator. The key is that both must evaluate to true If the And operator is to return a true. The Or operator is similar to the And operator, but only one of the two comparison expressions must be true for the Or operator to return true. Therefore, the expression 3 < 100 or 5 = 20 returns true, because the first comparison, that 3 is less than 100, is true. Even though 5 = 20 on its own returns false, the Or operator returns a true because at least one of the two comparisons is met. If both are met, the Or operator still returns a true. If neither comparison returns true, the Or operator returns false. The Not operator works with only one comparison and turns Its result into the opposite. Therefore, if the comparison 20 > 10 returns true on Its own, the comparison preceded by the Not operator, as In ' not (20 > 10) " ■ ' - ^ - ^ returns false. In other words, the Not operator returns what the following expression is NOT. If it's not true, then it must be false, and vice versa. Youll see these expressions frequently in Chapter 37 where we demonstrate the conditional constructions. Examples: if field 1 is true or field 2 is true then put true into answer repeat while theHour > lO-i and theHour < 1 1 — theHour Is a local variable • You Try It: Type the following messages Into the Message Box in Einy stack: put 1 into tempi > put 100 into temp2 tempi > 0 and temp2 > 0 tempi < 0 and temp2 > 0 tempi < 0 or temp2 > 0 tempi < 0 or temp2 > 100 tempi = 1 not (tempi = 1) 'jv, \(i U.;n -■■> & ■: 572 HyperCard's Programming Environment & ' ; (concatenate) ■ (concatenate and space) • Returns: The combined text string from two individual text strings When TO Use It: The concatenate operators are demonstrated frequently , in chapters about H3rperTalk commands. Generally speaking, the concatenate operators link two text strings together into one string. This is used primarily as a way of combining text components from diverse sources before putting the result into a container, like afield or variable. = A practical application of concatenation revolves around a system of ' ' naming cards in a stack in such a way that you can assemble the card ' ■' • name from various components before going to the card. At one stage of development of Bantam Electronic Publishing's Business Class™, - ' "5 for instance, cards with country maps contained a row of buttons linking to information cards about that country. The button scripts assembled the name of the Information card from two sources: the flrst „, item of a hidden text file containing one or more country names, and a text string in the button script representing the type of card, such as Currency or Air Travel (Figure 35-2) . When the user clicked on the Currency button in the France card, the button script assembled the information card's name by concatenating the country name, France, and a three letter code for the Cunrency card. "Cur." The script looks something like this: on mouseup put item 1 of field "Country Name" & "Cur" into goName go to card goIVame in stack "Currency" end mouseup Over in the Currency stack. France's card was named "FranceCur," and HyperCard zipped to that card as quickly as it could. Since the Concatenate command, by itself, abuts two pieces of text without any spaces, HyperTalk includes a shortcut to adding a space between the pieces: the double ampersand operator. This operator works Just like the regulsir concatenate operator but also inserts a space between the pieces. You can also link more than one concatenation together in a script line as well as a mixture of single and double ampersands. It's nsA uncommon to see constructions Uke field 1 && field 2 & field 3 in a script. Mathematic Operators 573 Figure 35-2. In Activision's Business Class™ stackuxire for tiyperCard, the button scripts linking country maps to information cards for currency, air travel and other data, at one time used the concatenate feature of HypetTalk, put item 1 of the long date && item 2 of the long date open file the date & the time You Tmr It: Type the following messages into the Message Box In any stack: put "Howdy" into tempi . , , put "Doody" into temp2 • - ^i-. put tempi & temp2 into message , . put tempi && temp2 into message , , put "It"s the " & temp 1 && temp2 & " Show!" . ' contains is in Returns: True or false, depending on whether one text string is In another. 574 HyperCard's Programming Environment When to Use It: You'll find times in your script-writing when you want to test whether a certain character, word, or phrase is Included In a container like a field or variable. For such a test, use the contains operator. The syntax Is as follows: contains meaning that the first parameter holds the text through which you wish to look for a match of the second parameter. The alternate syntax is is In For example, let's say that field 1 contains the text, "Larry, Mo«, and Curly." The following expression, field 1 contains "Moe" returns true. But the expression field 1 contains "Sarah" returns false. The operator performs strictly a text-matching task, ignoring whether the parameters are valid words or Items. Hierefore, the expression field 1 contains "r" returns true, although this fact doesn't tell you a lot, since there are three instances of the letter r in the container. Examples: if field "date" contains the long date then... repeat while temp contains the time if field "checkmark" contains "V" then go card id 1655 You Try It: Type the following messages into the Message Box In any stack: put "Four score and seven years ago..." into speech speech contains "four" speech contains "4" speech contains " " — a space between quotes speech contains "r s" ~ r, space, s "four score" is in speech (comment) Returns: Nothing. HypeiTalk skips the script line, When to Use It: While it's true that HyperTalk scripts are in more ofa natural language than most programming languages, it is still an excellent idea to place comments in your scripts to help you find Mathematic Operators 575 sections or long scripts or remind you later of the technique used to carry out a particular operation. When you type two hyphens in a script line (even as the first characters of the line), HjTJerTalk skips over the words following them on the line. This is where you can place your comments about the script. If your stacks are going to be used and customized by other people, then be as helpful as you can by providing memy clues in your scripts regarding techniques and philosophies about your stack and script- design decisions. You might even include instructions in the script for ways of customizing certain parts of It. ExAMPixs: put 1 Into X — X is local variable, used for counter, -- this section calculates the metric conversion... You Try It; Typing comments Into the Message Box Is a waste of time, since nothing happens. We have been using comments so liberally throughout this book that they should be rather familiar to you by now. Precedence While we've covered all the HypeiTalk operators, there is one aspect about them that is not obvious. If more than one operator or more than one type of operator is located in a single script line, HyperTalk obeys strict rules as to which operators are evaluated first— and it doesn't go from left to right. The rules are based a lot on algebra (don't run away!) and can be summarized here. HypeiTalk performs operations in this order: 1) Operators within parentheses are performed before those out- side parentheses. 2) minus sign (for a negative number) and boolean not 3) (to the power) 4) * / dlv mod 5) + - 6) & && (concatenate) 7) ><<=>=££ contains Is In 8) = <> ?t 9) and 10) or 576 HyperCard's Programming Environment What this all means Is that HypeiTalk picks apart a line of script and . . - calculates each operator in accordance with the priorities listed above, - No script line will contain all these operators, but HyperTalk sti ^ ;ri-,. adheres to the list. The importance of understanding precedence, as it is called, can h« , i; <; demonstrated In a simple comparison of two formats for the same arithmetic expression: Because of HyperTalk's rules of precedence, expression a) would evaluate to 30. Expression b) evaluates to 60. That's quite a difference for the addition of a couple parentheses, but those parentheses can help you direct HypeiTalk to interpret your intention (which was, in this case, to add 5 to 10 before multiplying the result by 4), 1, A lot of HyperTalk's precedence rules are almost automatic, For , ; example, the way you've learned about the And and Or operators, you pretty much expect the other arithmetic operators to have been completed before the anding and oring is performed. That's exactly hcift' the rules are already set. The important thing to remember is that when you assemble complex arithmetic expressions (including those using containers as numbers) , you should run a simple test with small values ' .'v like 1 and 0 to be sure the expression is evaluating correctly. If thw're " \ not, you may need to add a set of parentheses or two to force HypetTalk / into following your lead on how to evaluate the expression. a) b) 4 * 5 + 10 4 * (5 + 10) ^yl- v.- CHAPTER 36 Constants HyperTalk simplifies the entry op certain values that are normally DiFncuLT to get to from the keyboard, like the values for the Return or Tab characters and an empty string. These characters are given plain language words that substitute for the longer, more cumbersome ways of expressing them. For Instance, inserting a tab character between field entries in a Write To File command would normally require knowing the ASCII value of the Tab character and performing a numToChar conversion. Instead, HjpeiTalk gives you a constant, called Tab, which you use In the script as if it were a standard text character. In this section, we examine each of the constants HyperTalk provides its programmers. Some constants— like true, false, up, and down- HyperCard uses to convey information at the return of a function or operator. true false up down When to Use It: If you've studied HyperTalk functions and operators, you've seen that HyperCard uses these four constants frequently. True and False are often the result of comparison operators, while Up and 577 578 HyperCca^'s Programming Environment Down represent the condition of various keyboard keys and the mouse button at the time a function executes. But HyperCard doesn't have a monopoly on these functions. You aic free to use them as you see fit. In fact, programmers commonly apph- the True and False constants to set variables so that they behave as markers for where they've been. For example at the beginning of a long script, the programmer may set a variable to true {put true into markeil. If the script includes a decision point (see chapter 37) and the execution proceeds down one path, the script in that path may set the variable to false. Later in the script, where execution continues regardless of Intervening paths, the script can test the variable. If the variable returns false, the script knows one path has been taken and can then | act accordingly. This methodology is often called setting flags, because \ the variable, by its true or false setting, flags the script as to which route \ the script has followed. j Also, as you'll see in chapter 37, any variable set to true or false can substitute for a longer comparison operation that also returns true or | false. Therefore, instead of saying if marker is true then beep, you can simply say if marker then beep. The variable "marker" by Iself returns its content, which could be true or false. That meets the requiremenl of the conditional construction. Examples: : if the Optlonkey is down then go card id 100 repeat while marker If the ShiftKey is down and the sound is done then go Home Tou Try It: The right way to experiment with these constants is in the context of if-then structures. Since you cannot execute if-then struc- tures from the Message Box, place the following handler in anew button script in a blank card of the Address stack. Then click the button while holding down one or more modifier keys, on mouseUp : , put 'The Option Key is " & the optlonKey hito line 1 of field 1 put 'The Command Key is "-i & the commandKey into line 2 of field 1 put 'The Shift Key is " & the shiftKey into Ihie 3 of field 1 if the optlonKey is down or the commandKey is down-, or the shiftKey is down Constants 579 then put "Modlfier(s) in eflFect. " into line 4 of field 1 else put empty into line 4 of field 1 end mouseup empty When to Use It: The Empty constant is the same as the null text string (that Is, two quotation marks with nothing in between, ""). Not only Is it easier to put an empty constant in a container to clear it, but it is also more natural- sounding tn a script to test for whether a container is empty than to bother with the null string. , ' put empty Into field 1 i ' . ' if field "Name" is empty then ask "Enter Name:" You Try It: Type the following messages Into the Message Box whUe viewing a blank card In the "Address" stack: put "hello" into field 1 ' ' ' !'/ put empty into char 2 of field 1 - • • ; i ^ ■ put "everybody" into Itne 2 of field 1 - ' put empty tnto line 1 of field 1 ' • = ^- quote ; .--C^R..-^ --c^- >-; ^ When to Use It: if you've ever tried to place a quotation mark In a field or variable, you probably were frustrated, because HjrperCard sees a quote mark as the beginning or end of a text string. You couldn't place a quotation mark Inside two quotation marks. That's why HjrperCard has a quote constant. It substitutes for a quotation mark in a text string when that string should contain the quotation mark. ^eample: put "Say " & quote & "Hello" & quote & " to everybody." put "Coordinates: " & field 3 & quote && field 4 & YotJ Trv It: Type the following messages into the Message Box in any stack: 580 HyperCard's Programming Envimnment put "He said, "My name is Joe." "into message -- not allowed put "He said, " & quote & "My name is Joe." & quote into message retiim space tab _ When to Use It: These three constants substitute for keyboard charac- ters. Return and Tab are used most often In the Write to file command, In typical scripts built around the Write to file command you must Insert field and card (record) delimiters. This assures that the external Macintosh application can read the information from the text ffle created by HyperCard. If information in a text field needs additional spaces between items, a script can use the Put command and the space constant to insert a space where necessary. The alternative would be to put a text string consisting of quotation marks surrounding one or more spaces. The dlfilculty with that construction is that it becomes very difficult later to determine exactly how many spaces are between the quote marks. With the space constant, you can tell exactly how many are there, because there is one constant per space. ? ;/ - Examples: put space & space & space after word 1 of field 3 read from file "Database" until tab write return to file "Expense Report" You Try It: Use a blank card In the Address stackfor these experiments. - - Type the following messages into the Message Box: put 'Three blind mice. See how they run." into field 1 put space & space after word 1 of field 1 put return after word 1 of field 1 put return before word 2 of field 1 put return before word 3 of field 1 formfeed ^ - i-^^.t^- , y^. linefeed When to Use It: The formfeed and linefeed constants are control characters usually used for printers {although some communications services respond to the linefeed character). These two characters ait I Constants 58 1 not available from the keyboard, so HyperCard provides a way to send them primarily to text flies you create with the Write command. A linefeed character (ASCII value 10) differs from return. On telecom- munications terminals (and also on the old teletype machines), a return character sends the print cursor (or printhead) to the left edge of the screen (or page) without advancing to the next line. To advance the cursor (or paper) to the next line, the Linefeed character command is required. Today, most printers automatically insert a Linefeed com- mand when they receive a return command (this ability is one of the settings of the small DIP switches inside dot -matrix and letter-quality printers— laser printers don't need to bother). If you find that the text files you write from HyperCard cause the printer to print text all on the same line without advancing the paper, either change the printer's switch setting or include a linefeed character along with the return character in the printing script. Formfeed Is another character (ASCII value 12) that causes the paper to advance to what the printer considers to be the top of the next page. The need for this constant will be rare, but it Is here if you need it. Examples: write return & linefeed to file "Print File" write formfeed to file "Pages and Pages" You Try It: Since you cannot see these characters on your HyperCard screen, there is little need to experiment with them here. To prove these constants are legitimate ASCII characters, however, type the following messages into the Message Box: the chaiToNum of llneFeed the charToNum of formFeed nils concludes our discussions about functions, operators, and constants. There is one more fundamental subject area you should know about before we get into some sample HyperTalk applications: control structures. That's the subject of the next chapter. TOl ms are CHAPTER 37 HypeiTalk Control Structures Much of what we, as humans, do every day can be described in terms of what HyperCard calls control structures. The two basic structures Involve 1) making simple decisions and 2) repeating actions with slight vari- ations. In the course of a day, you make many decisions, most of them unconsciously. For intance. If the television set Is too loud, then you turn the volume down. If it is getting dark, then you turn on a light. If It is a nice, warm day and if you have a free moment, then you'll step outside for a breath of fresh air. You may make thousands of these if- then decisions per day. HyperCard, too, can make if-then decisions. A number of daily tasks are repetitive actions. Again, you probably don't recognize such tasks as being repetitive. But, even while you're reading this book, you're performing a repetitive task: reading one word or phrase at a time, then advancing your eye to the next word or phrase. You continue repeating this action until you finish the book or stop reading because you're tired or have something else to do. The same can be said for paying bills from a checkbook. The basic action, writing a check. Is repeated until all the bills are paid or your checkbook balance Is zero. Some details of each step In the repetition are different, like the payee and the amount, but the basic action is still repeated. HyperCard allows you to program similar kinds of repeated actions, allowing for slight modifications at each step. The HyperTalk syntax provides several construction options for tf- then and repeat control structures. Each has a specific purpose that 583 584 HyperCard's Programming Environment affects the flow of logic through a HypeiTalk script. We'll discuss each one in detail, following a format similar to what you saw for commands and functions earlier. Rather than offer separate experiments for you to try, we'll show you real-life examples in each discussion, which you can place in button or card scripts to try yourself. These constructions generally involve multiple-line scripts, so the Message Box approach is out of the question. All examples will be presented in such a fashion that you can write them Into card scripts attached to blank cards in the Address stack. Each sample script will be a complete message handler with its own name. To try the script after typing it into the card's Script Editor, tjrpe the name of the message handler into the Message Box (for example, if the message handler starts with onJoufTimes, then t)'f( fouiTimes into the Message Box), HyperCard, as you'll recall, sends the message from the Message Box to the current card. If-Then Decision All HyperTalk if-then constructions have one important characteristic in common. Each one begins by testing whether a certain condition is true. By that we mean that whatever expression is under test, it must evaluate to either a true or false. If the result is true, HyperTalk progresses down the special path set aside for it whenever the expres- ( sion returns true. If the result is false, HypeiTalk ignores the special ,y path and zips to the next regular line in the script. This process is pictured in Figure 37-1. If you think back to the last chapters, which covered functions, , - , operators, and constants, you'll recall that a few functions and many ;•; , operators return either a true or false. Any one of those expressions may ; i( . be used in the test part of an if-then construction. You'll commonlytest , : for things like: whether a container is equal to (or less than or greater , than) a certain value; whether a container is empty; whether a container holds a specific text string; whether two contatners are equal : (or less than or greater than) each other. You may also test directly far the true or false setting of properties, like whether a button Is highlighted. All if-then constructions, therefore , begin with the word "if," followed ;;•.» by the true/false expression and the word "then." Here are some examples of this prefix: , if X < 3 then... if item 3 of the long date > 1989 then... if field 3 <> field 1 of card id 7067 then... if field "Name" is empty then. . . HypejTaik Control Structures 585 Figure 37-1. The result of a decision is either true or false. A script can perform different or extra steps based on the results of a decision. With the help of the And and Or boolean operators, you can set more than one expression for the true/false test. For example, if you want H3rperTalkto execute some special Instructions only if the current year Is between 1980 and 1990 (inclusive), you could first put item 3 of the long date function into It. Then set up the following prefix to an if-then construction: if it > 1980 and it < 1990 then... Following the rules of the And operator, the expression wiU return a true only if the year is 1 980, 198 1 1990. You can use the Or operator to allow execution of the special code only if the month function returns 1980 or 1990 in the foUowing prefix: if it is 1980 or it is 1990 then... , Using the Not operator, you can test for all conditions except one. All years other than the one specified will divert to the command(s) following the "then" part of the construction: if it is not 1984 then... 586 HyperCard's Progranunir^ Environment While all the if-then constructions share the true/false structure, what distinguishes each of the three is what happens after the "then." That's what well focus on in the descriptions of each if-then construc- tion. if.. .then / / FORUATS: if then If then if then end if When to Use It: This Is the simplest of the if-then constructions. It presumes that you have an alternate command path set for instances in which the true/false expression returns true. When the true/fals« expression returns false, the alternate command path is not canled out. When you have a single command as the alternate path, use the simple, one-line if. . .then format. When the one line command is a lonj one, it may be more convenient to use the second format. When multiple commands apply to the alternate path, use the third format The HyperTalk Script Editor automatically indents commands beneath the tf statement. But also notice that multiple command lines require ' - . an end if marker to let HyperCard know that it has reached the end of • the if commands. A is any HyperTalk command that you would normally put at the beginning of a script line. Use this construction whenera your script needs to make some kind of simple adjustment whenever a certain condition is true. Examples: * " on insert if field 1 is empty then put the long date into field 1 get item 3 of field 1 if it < 1988 then put Tour clock may be off' end Insert , on openCard if field 1 is empty then . ' ' ' HyperTalk Control Structures 587 put the long date into field 1 put the time into line 2 of field 1 end if ask "Is the current time " & line 2 of field 1-t & " correct?" with "OK" or "No" if it is "No" then put "Please adjust time in Control Panel." end openCard ■'\ if... then... else Formats: if then else if then else . * if then - • - - else ^ If then else end if tf then else end if When to Use It: Use the If-then-else construction when you have two possible side paths for H3rperTalk after a decision , one path for true , one for false. When the expression returns true, HyperTalk pursues the first path (the one after the "then"); when the expression returns false, HyperTalk pursues the second path (the one after the "else"). Figure 37- 2 Illustrates this execution path. You can use this construction even if you have only one command for each condition or different numbers of commands for each. Since the true/false expression will return one of those two possibilities, the 588 HyperCard's Programming Environment Figtire 37-2. An if... then... else construction lets your script perform, two distinct op€ratior\s based on the results of a decision. script will execute one of the two banks of commands before proceedlnj through the script. Only when the else part of the construction contains multiple command lines do you need the end if marker, as in the last two formats, above. * Example: on quiz ^ put empty into message ask "What is another name for Britain?" . ,^ If It Is "England" or It is "United Kingdom"-. " or It is "U.K." then put "Correct" into message else beep answer 'Sorry. Try again?" end if end quiz HypeTTalk Control Structures 589 Nesting If-Then Decisions You may place an if-then construction within another If-then construc- tion— a format called nesting. It's not uncommon to require nested if- then constructions, because the world is not black-and-white (or true- and-false). Even when something tests to be true, it may still undergo further scrutiny to help narrow the decision process. The best way to observe this is to watch It in action Inside a real script. The following message handler presents a dialog box requesting whether you wish to know how many days are In the current month. It then reads the current month from the Macintosh clock and makes further determinations before presenting the reply In another dialog box. on hathMonth answer "Do you wish to know how many days In this month?"-, with 'Yes" or "No" If it is "Yes" then get the date ' - ' -f r, » convert it to dateltems put item 1 of It Into year , ■, ■ ■ put item 2 of It into month if month is 4 or month is 6 or month Is 9~, or month is 11 then put 30 Into howMany . , else put 3 1 into howMany If month Is 2 then If year mod 4 = 0 ■:'''>^ ' then put 29 into howMany -.(-ff- -o' else put 28 Into howMany -?r^ . ^ ' end if answer 'This month has " & howMany & " days In It."' else answer "Just thought we'd ask" end hathMonth This may seem to be an extreme case, but it does demonstrate that you can nest if-then constructions quite deeply, mixing sungle and multiple command line constructions as needed. And, despite what seems to be many lines of code, HyperCard goes through its paces rather quickly. Try the message handler above to see for yourself. Place it in a card script and type hathMonth into the Message Box. 590 HyperCard's Programming Environment Repeat Constructions HyperTalk offers four different repeating control structures from which to choose: repeat for, repeat until, repeat while, and repeat with. While , , ; . their uses are quite different, they share two common characteristics, -;. The first characteristic is that in the same line as the repeat command you will be providing information that controls when the repetition Is , . . to end. Sometimes the repetition ends after a specific number of times; at other times, the repetition ends only upon a certain condition being met, a condition that changes each time through the repetition, i Repetitions like these are sometimes called loops, because the execu , f . . ^ , . tion of the instructions runs in circles until it can break out of the cycle. . >! Th^ second characteristic has to do with the ending of the repeat ; construction within the script. The command End Repeat must be entered on its own line at the close of the repeat grouping. This is like a marker to HyperTalk so that it knows how far down the script to p . before looping back to the beginning of the repeat construction. Now we can look at each repeat construction in detail. repeat for Format: repeat [for] [times) end repeat When to Use It: This repeat construction repeats the indented com- mands a fixed number of times. The parametermay be a plain number, an arithmetic expression, or a container (provided the container evaluates to a number). EXABIFLBS: ' on addCards ask "How many new cards do you want?" repeat for it doMenu "New Card" t;!?? .:K \ put "This is a new card" Into field 1 end repeat end addCards on showTlme ,t , put "Hooray for HyperCard!" HyperTalk Control Structures 591 repeat 10 times put space before msg ' ' r-: : : . . 3 end repeat repeat 20 times , ' ' put space before word 3 of msg ' beep 1 ' --'^ end repeat '; ' ' repeat 20 times ' ^ ' ' ' " ' put empty Into char 21 of msg : . end repeat ' ' repeat 10 times ! . •:,!? ) put empty into char 1 of msg . end repeat al M'L' ' end showThne ' repeat until a ,.ii> -au * Fobmat: repeat until end repeat When to Use It: In the Repeat UntU structure, the Indented commands are executed until the true/false expression returns a true. In other words, if the expression returns a true the first time, none of the indented commands are executed. But If the expression is false, the loop starts and continues until the expression returns a true. Obviously, the commands inside a Repeat Until construction must have some effect on the factors in the true/false expression. If nothing about that expression changes, the loop wlU drone on endlessly. In fact you will have caused what is known as an endless, or Infinite, loop. Thfe only way to break out of an infinite loop is to hold down the Command key and press the period key. That key combination halts a HyperTalk message handler in its tracks. A common application for Repeat Until Is to keep a loop going whUe waiting for a mouse click. There doesn't have to be a command between the repeat and end repeat parts of the construction. If you include no command lines between the start and end of a repeat, the repeat loop keeps cycling very tightly until the true/false expression returns true. As an aid to debugging Repeat Until loops, you can place a command that puts the value of the changeable variable into the Message Box. 592 HyperCard's Programming Environment That way, you can keep an eye on what's happening to your tnie/false expression as the repeat construction cycles round and round. EXAMFLBS: onjumpWeeks - . . repeat until the mouseClick get number of this card go card (it + 7) wait 1 second ^ jj, end repeat end jumpWeeks , repeat while Format: repeat while end repeat When to Use It: The Repeat While construction is essentially the opposite of the Repeat Until construction. In this case, the indented commands are carried out as long as the true/false expression remains true. If it is false to begin with, HyperTalk will skip right past it. As with Repeat Until, your indented commands must have some effect on the Items being compared or measured in the true/lalse expression. If these factors never change , then your script will be in an infinite loop. Use the Message Box debugging aid with Repeat While, too. Place a command among the indented commands that isolates the changeable value and put the results into the Message Box, You'll then be able to watch the value change each time the loop makes a cycle. If the loop works too fast for you to watch closely, then insert ujoit I second as i , another command inside the loop. Examples: .<^,:-'-Hn. c;." i-- on tunes put the random of 60 into note ' if note < 40 then put 40 into note ' : ' ' ■ if note mod 2 is not zero then add 1 to note - "f- ■ ' ' repeat while note < 82 ' - ' put note !-'..-^>v ^ - - play "Harpsichord" temp 700 note HyperTalk Control Structures 593 add 2 to note ' end repeat . ■ w;-, end tunes repeat with ,;r Format: ' ■ . ■ . - .-ni.i^^ 4- repeat with = to . rf ' J ■ end repeat •> - ■ . ,,i repeat with = down to .vj.-. « , end repeat ^- : . r (.,..■•..— .. , Whem to Use It: WhUe the Repeat With construction may seem like the most complicated of the four. It Is perhaps the most commonly used. With this construction, you can both initialize a variable and set bounds for It. Each time through the loop, the value of the variable is increased or decreased by one. The loop continues cycling until the value of the variable equals that of the second number. This Is so valuable because you can use the variable within the indented commands to perform actions on any numbered group of objects or components. Therefore, if you Initialize a variable "a" and give it the bounds 1 through 5. each time through the loop you can issue a command like put the date into field "Date" of card a. The first time through the loop, the date goes into card 1; the second time through, the date goes Into card 2; and so on. Parameters for either boundary number may be a plain number, an arithmetic expression, a function, or a container. Therefore, if you wish to perform an operation on every field in a card, the repeat construction would stari; out like this: repeat with x = 1 to the number of fields Then, within the indented commands, the instructions calling for a field designator would look like this: put empty into field x TTie beauty of this repeat construction is that you can condense an awful lot of HypeiTalk code into just a few lines by repeating the same code over and over, but Incrementing (or decrementing) the object or container designator each time. Whenever you notice that a script 594 HyperCard's Programming EnviroTiment repeats the same commands to similar kinds of objects, you probably have a candidate for condensation with the Repeat With construction. EXAMFLf*. on makeCards ask "Please enter the starting date:" with the date convert it to seconds put It into start ask "Please enter the ending date:" ■ ' convert it to seconds put It into finish put finish - start into howLong divide howLong by 24*60*60 ' repeat with count = 1 to howIx»ng ■ doMenu "New Card" put "Day " & count into field "Which Day" put start into field "Date" convert field "Date" to long date • • : '^-^ ■ V add {24*60*60) to start ■ . ' '■ end repeat end makeCards Modifying Repeat Execution Order Normally, within a repeat construction the commands are executed in the order in which they appear. TTiat's as It should be. But there may , be times when you might not want the cycle to include some com- ;s mands. In other words, you'd like the cycle to skip the remaining commands and start over at the top of the cycle, incrementing tht counter, if it's the Repeat With construction. HypeiTalk has a com- mand that does that: Next Repeat. ; , . You can also exit a repeat construction In the middle of it, If a condition you're looking for is met before execution reaches the bottom and starts over. The command that takes care of that is Exit Repeat. next repeat Whf.n to Use It: You can set up any valid conditional test (if-then) ulthin the indented commands of a repeat construction, In such a way thata '■ test returning true executes the Next Repeat command. A skeletal " ' ' repeat script set up this way would look like this: HypeiTaUc Control Stnwtures 595 repeat until . ; v • , , : - • ■ ' .^S'^ - if then next repeat ■ ! ' ■ r ; end repeat ' ' ' HyperTalk would start following the repeat commands as usual . If the conditional test after command 2 proves true, the next repeat command tells HypeiTalk to loop back to the top of the repeat and start over. If the repeat construction had been the Repeat For or Repeat With, the counter would have Increased by one. Hie Next Repeat command Is used to trap a special case in a repeat loop and prevent further commands within the repeat to be executed. A practical appHcation for this construction is within a repeat with loop in which you want the counting variable (that is, the "x" in repeat with jc = 1 to J 00) to increment by numbers other than 1 . If. for instance, you want to use the counting variable only when it is even, you could place an If-then statement at the very beginning of the repeat loop that tests whether the counter mod 2 is not zero. If it's not (meaning the counting variable is an odd number), then do a next repeat without performing any other commands in the loop. Experienced BASIC programmers will recognize this method as an equivalent to the REPEAT. . .STEP con- struction. , :■: -nv ;^ r.l i'/ <• repeat with count = 1 to 14 if count mod 7 is 0 then put "No scheduled work on Sundays" -i into line count of field 2 next repeat end if put "Day " & count into line count of field 2 end repeat r . > ; ^ end plan When to Use It: You may also test for a condition within a repeat loop that is different from the one the repeat is looking for. For example, the ExAims: on plan edt edt edt repeat if ■chandler name> 596 HyperCard's Programming Environment repeat may be waiting for a mouse click all the while some math is going on within the indented commands. If you want to exit the repeat without a mouse click when the math reaches a certain value, you'd test for that value and issue the Exit Repeat command. The skeletal construction looks like this: repeat until the mouseClick -- does things to the contents of field 3 , if field 3 > 100 then exit repeat .<;t end repeat In this case, the loop will stop before a mouse click if the content field 3 grows to over 100. This is assuming, of course, that commands in this loop have some effect over field 3 during execution of the loop. It also turns out that the Exit command Is rather universal, cov if-then constructions and message handlers in general. Within a message handler situation, the Exit If command comes in quite handy . ' when the script needs to perform special actions only when the if-then : ■ -■ ' condition is true. All the rest of the commands in the message become ' superfluous, so you can break out of the entire handler. This speeds execution, because HyperCard doesn't have to evaluate other if-then decisions later in the handler. When the handler exits, then it's i\ through. Examples: on mouseup " — monthly interval between calendar cards If field "interval" is "monthly" then go next card exit mouseup ^. .^^j-;^ end if ^ '-^ if field "interval" is "yearly" then 9^^' " get number of this card ■'f^*^ add 12 to it go card it else put "Sorry, cannot fmd the Interval— go to Setup Card." end mouseUp p&SS When to Use It: Occasionally, you will want to trap a ^lyperCard message or other kind of message whose primary handler is way up HyperTalk Control Structures 597 HyperCard hierarchy. If you'd like to add some extra feature to the handler or trap the message when it has a particular pEirameter (like a menu item name), issue the special command, and then send the message on its way up the hierarchy, as If it had never been trapped. You send it on its way with the Pass command. The one parameter to the Pass command is the name of the message that you originally trapped for. For example, if you have a button script that traps for mouseUp and there Is a background script also for mouseup, your button script would trap the mouseUp message first. After it has done its thing, it may then pass the mouseUp message to the next level up the hierarchy. When the background mouseUp message handler gets the mouseUp message, it will not know that the message had been intercepted anywhere along the path. Trapping for menu items is a popular application for the Pass command. Since the doMenu system message comes with a parameter consisting of the name of the menu item, you can perform operations in a handler for one or more menu items. But you must also pass the message to HyperCard so it can respond to other menu items. If you don't pass doMenu, the system message would be forever trapped in the handler- one method, by the way. of protecting read-only stacks from saboteurs. Examples: on doMenu whichltem if whichltem is "Help" then go card "Custom Help" else pass doMenu end doMenu This concludes the discussion about HyperCard's control structures. In the following chapters, we'll be applying the concepts learned in the preceding chapters. Together, we'll build some practical HyperCard applications, while you leam more about the commands, properties, functions, operators, constants, and control structures in action. CHAPTER 38 Introduction to Applications Each of the next six chapters contains detailed specifications for HyperCard applications you can use as they are or adapt for many other purposes. The intent of these examples is to demonstrate HyperTalk techniques and strategies In real working environments. The applications cover a wide range of complexity, from a simple "brute force" stack (simple to implement, although an experienced HyperTalk hand would be able to accomplish the same stack functions with fewer cards) to a stack whose scripts run a couple of pages of Script Editor printout. For each stack, we start with an overview of how the stack operates, so that you can appreciate its functions and the interaction among cards, buttons, and fields. Then we let the stack itself do most of the talking. We extracted the object scripts and properties directly from the stack and reproduced them here. When additional comment is neces- sary, we help explain HyperTalk constructions that may be new to you or that are representative of techniques you should strive for. In all cases, the scripts are examples of HyperTalk programming style and pracUce as envisioned by the language's creators. Wherever possible, we tried to use the graphic elements supplied on HyperCard's ideas disk. These stacks are supposed to represent stacks that anyone- including those with less than spectacular painting tool mastery- can recreate. Those Ideas disks are valuable resources you should use regularly in your stack design. 601 602 Applying HyperCard and HypeiTalk The only way to become proficient in HypeiTalk is to use It on real stacks. Start by recreating the stacks in the following chapters. Thtn modiiy them to suit your particular applications. Always be on the lookout for techniques that might apply to the things you want to do with HyperCard. As you build a HyperCard stack, do it in stages, testing each message handler as you go. When you get alert messages Indicating that HyperCard can't do something or doesn't understand a partlculai construction, click on the alert box's Script button to zoom in on the problem. Make the necessary repair and test the handler again. Keep at it until you've worked out all the kinks. Then move on to the next handler. Another useful technique when designing your own scripts from scratch Is to get the functionality of the script working, even If the code is not especially elegant or compact. Once the handler is doing what It should, go back to it and look for ways of making it more efficient and simpler, or perhaps for ways that it can be shared by other objects when placed at a higher level. You'll see some examples in the next chapters in which there are no button scripts in a stack (at least for the main action buttons). The handlers that perform the action are in the background or stack object, taking their cues from the name of the button clicked by the user ( the target, in HyperTalk functions parlance), ■' ' One script ends up performing the tasks of a dozen. ' ^ • • But don't worry if you cannot seem to make your scripts as Ughtly woven as the examples we show here. The fact that you can make a ■ 1 stack do what you want it to do Is a sigruflcant accomplishment- and very much in the spirit of HyperCard. A Useful Utmty ScHpt Each time you create a new HyperCard stack, it is helpful to have a Home Stack button created so you can go to that stack easily. That way, you won't have to tty to find the stack with the Open Stack... method, Here's a suggestion. In your Home Stack, make a new card immediately after the Home ^ , card. Name it "My Stacks, " both in the card name property (ushig the Card Info. . . dialog box) and in the title field at the top of the card. If that ; field is locked , double-click the field with the Field tool, and change the ' Locked Text setting to off. * , Then add the following handler to your Home Stack script. Use It by typhig makeButti)n into the Message Box while in the new stack you're making. The handler makes a button of whatever stack you're hi and Introduction to Applicaiions 603 places It in this My Stacks card of the Home Stack. It leaves the Button tool selected so you can drag the button to an empty spot on the card. The next time you wish to go that new stack, simply click that button. Here's the handler: on makeButton put the short name of this stack into stackName go card "My Stacks" of "Home" • set lockScreen to true doMenu "New Button" set rect of button "New Button" to 200, 100.280,160 set icon of button "New Button" to 1000 set showName of button "New Button" to true set style of button "New Button" to transparent set name of button "New Button" to stackName put "on mouseUp ' into newScrlpt put "go to" && StackName-. into line 2 of newScript put "end mouseUp" into Une 3 of newScript set script of button stackName to newScript put "Now drag the button "&-, "to the desired location. . .and type Command-Tab" end makeButton , ^ Enjoy! . CHAPTER 39 A Corporate Directory When a company starts spreading its people across several buildings and shifts people around offices regularly, it becomes important that both employees and guests find their way to offices quickly. The corporate directory stack is an application that can be recreated quite simply, and without too much artistry. The stack environment shown here consists of a single stack with three backgrounds {although in practice, it would contain many more). If the company has thousands of people, you might prefer to divide the environment into two or three stack files. The first background consists of a Staff Directory card (Figure 39-1), which contains Information about each person employed by the company, items in the card are filled in as individual text fields. Most of the buttons and their actions should be familiar to you by now. The arrow buttons take you to the previous and next cards In the stack. The Home button takes you to the Home Stack. The Sort button presents an answer dialog box with options for sorting by name or department. We'll get to the Print button in a moment. Next to the Extension field is a telephone button, a click of which causes the stack to dial the extension listed in the field. In that button's script is also a second possibility. In case the extension is actually an outside phone number ; r- Overview 605 606 Applying HyperCard and HyperTaJk ^ t File Edit Co Tools Objects Corporate Staff Directory Name : ,Timothy..Newton 0 0 Position : Vice President^ Corpora^ ^ Department : .Ixecul|ve.Admlns.tratlQn. „ [_Sorrj Exteinsion: ,.,5.a9.9 ® QrintJ Location ; .HQ£th...Bmld.ing^...3..l.2. □iiiiiii find f Figure 39-1. (that is, Is longer than four digits), the button dials a 9 and the number In the field (presuming the stack is being used on a corporate phone system). The See Map button Knks the Directory card to cards in the not background. In this second background are a few cards containing maps of the entire corporate grounds (Figure 39-2). Each card higii- lights the building in which the person in the Directory card is located, Therefore, there are only as many cards in this background as there are buildings to highlight. Each card's name is the name of the building, so the handler in the See Map button (on the Directory card) goes to the card whose name is the first item of the Location field in the Directoiy card. In the campus map background is a button called Zoom In. This button takes the second item of the Directory card's location field, tiie office number, and searches for that number in a text field in the third background (Figure 39-3) . In this third background is a floor plan of one wing of one building. Each card has a card field with the number of a different office, and that office's cubicle is filled with a pattern. Note that the pattern and the field are in the card layer, whUe the rest of what you see Is in the background layer, j'^, , 608 Applying HyperCard and HyperTalk When you zoom Into this card, the person's name from the Director)' card goes into the field at the upper right. Three buttons offer you additional navigation from here. When you click on the small represen- tation of the building at the upper left, you go back one card, to the campus map. The Home button takes you Home, as you'd expect. And when you click on the cards bu tton at the upper right, you go back to the Directory card from which you started. Notice that the three most- often-used buttons— See Map, Zoom In, and the cards button- m located in the same spot on the screen. That way the browser does not have to shift the mouse around the screen to follow the most common navigation path. Back on the Directory card, the Print button performs an Open Printing with Dialog command, which lets the user set how many pictures should be printed per page. Then the button's handier performs the electronic equivalent of clicking on the See Map and Zoom In buttons, grabbing a snapshot of each of the three cards alongtheway for printing. A visitor to the company, for example , may want a printout as a roadmap to the person he's seeing. Scripts and Properties What follows are the scripts and properties for each of the objects in tlie Corporate Directory stack. Stack "Corporate Directory" I bkgnd "Directory" Script - i on openBackground set loc of Message Box to 19,293 doMenu "Find..." -- in anticipation of needing to Find end openBackground . ^ ^ 1 button "Prev" , , '\ Properties ^ 1 i LocaUon: 428,93 "X . 'T. ' ~ "'"^ ■ Rect: 414,81,442,106 ~ ; * ' ' ' ' i AutoHillte: true 'i - - ShowName: false Hilite: false ' Style: transparent " ' Icon: 1014 Visible: true A Corporate Directory 609 Script on mouseUp " visual effect wipe left go to prev card of this background — keeps browsing within Directory cards ; end mouseUp ,",■■,(:• button "Next" ]' " '^'^^'-- '^ ■ a' ^ • Properties -; . Location: 473,93 '[[ , ■/ " ' ' / Rect: 459,81,487,106 " , ^ . . , AutoHilite: true , r "-. ■ . ShowName; false , Hilite: false ' ' '"' ' Style: transparent ", ^ ~;-;r Icon: 1013 Visible; true Script ■ V ; \, . on mouseUp visual effect wipe right • • > go to next card of this background end mouseUp ' ; ' ' button "Home" Properties Location: 451,127 Rect: 433,113.469,142 , . , ^ ' . AutoHilite: true ' , ' " . ' ' ShowName: false , . /, . ^ ' ' . • Hilite: false 7' ^ . . Slyle; transparent Icon; 20689 Visible: true Script - on mouseUp ■ , : - go home '' .' v s end mouseUp ' ■ . button "See Map" Properties Location: 451,45 Rect: 418,34,485,56 ; AutoHilite: true ShowName: true 610 Applying HyperCard and HyperTalk Hilite: false Style: roundRect Icon: 0 Visible: true ., v,.' Script - J, ':ri/^V; : - on mouseup global name,location ~ used by other buttons and cards push this card — need this to return later put field "Name" into name put field "Location" into location go to card item 1 of location — the name of the Campus Map card end mouseup button "Sort" .t Properties ■ Location: 451.163 Rect: 418,152,485,174 ' AutoHilite: true ; ShowName: true ; " i r.n Hilite: false ■-: . •;■ Style: roundRect Icon: 0 Visible: true Script on mouseup answer "How would you like to sort this dlrectoiy?"-i with "By Name" or "By Dept." or "Cancel" If it is "By Name" then sort by last name of field "Name" else if it is "By Dept" then sort by field "Department" end mouseUp button "Dial" Properties Location: 238,201 Rect: 224,190,252,213 AutoHilite: false ShowName: false Hilite: false Style: transparent Icon: 10610 Visible: true A Corporate Directory 611 Script on mouseUp ' vo ih, put msg into temp - save Msg for later ; * put "Now Dialing " & field "Name" &"..." into msg if the length of field "Extension" < 4 then dial field "Extension" • • else dial "9" & field "Extension" '-.''^ " dialing an outside number put temp into msg -- restore original Msg contents end mouseUp button "Print" 'q- ; .I's?? Properties ■ . ' isi'' Location: 451,193 . . o Rect: 418.182,485,204 ' -i' ■ AutoHilite: true ■ >^;'.' - .>^' ,^ . =^ . ShowName; true Hilite: false ;:"V, ' ! Style: roundRect Icon: 0 , . Visible; true Script ' ' ' ■ ' ■ ' ' on mouseUp ''Iao.^^.:^. ; open printing with dialog print this card send mouseUp to bkgnd button "See Map" s print this card send mouseUp to bkgnd button "Zoom In" ... j . .^ r, print this card close printing • ^ send mouseUp to button "RetumToDirectoiy" ' ' end mouseUp ' ' Comment: By sending mouseUp to each of the buttons mentioned in the script, the handler is doing the same as the user clicking the buttons. Going to each card, the handler then puts the printed version of the card into the printing queue. At Close Printing, the queue is flushed out, and the last page of printing is sent to the printer. field "Name" i .c. Properties ^ ; Location: 233,95 , Rect: 70.85.397,105 - " ' ' L ' Applyir^ HyperCard and HypefTalk LocltText: false ShowLines: true WideMargins: false . ,... ,!.(;. Style: transparent . • ; . .. Text Align: left j ! V ' Text Font: New York ^ ! . / Text Height: 18 ,<>,,•. i ' • • i > : Text Size: 14 .dr-T ' , V r' i Text Style: bold , ' , , r Visible: true , field "Position" Properties Location: 240,131 . . k Rect: 83,121,398,141 H: (all other properties same as "Name") field "Department" Properties Location: 256,167 ' Rect: 114,157,398,177 (all other properties same as "Name") ^ field "Extension" , , Properties , . ■ Location: 153.203 Rect: 97,193.209,213 (all other properties same as "Name") field "Location" Properties , ' Location; 242,240 Rect: 88,230,397,250 (all other properties same as "Name") bkgnd "Campus Blap" ,: . . Script ■ - - ■ on openBackground " ' " ' : ' ' hide message ' ' ' ' : ■> end openBackground on mouseup — cHcklng on the card brings you back to Directory pop card end mouseUp A Corporate Directory 613 button "Zoom In' Properties Location; 450,49 '' ^ Rect: 418,38,483.60 1 : ; ; . i AutoHUite: true ^- ■ ' ShowName: true • Hmte: false ' Slyle: roundRect " ''; * Iconic Visible: true " • Script on mouseUp '■' ' '•■ global location push this card -- pushed atop Directory card visual effect iris open find item 2 of location v ,. . , , end mouseUp , . . on openCard .-j ^.^n;;,,,- ■ , • ^ global name . ^. f ; , put name into field "Name" ~ reminds browser who he's looking for end openCard , j , -d *, / button "RetumToMap" ^ : 3: !:»c Properties >' j Location: 53,51 Rect: 25,30,82,73 ju^*' o -= t t? AutoHilite: false V ^ ShowName: false < Hlllte: false , Style: transparent , ' Icon: 0 - Visible: true Script , , ' on mouseUp bkgnd "DetaU-North West' Script 31; -n: pop card end mouseUp — go back to Campus Map card 614 Applying HyperCard and HyperTcdk button "RetiimToDlTectory" Properties Location: 454,40 v\ Rect: 437.28.472.53 r AutoHllite: true ShowName: false Hllite: false Style: transparent Icon: 17481 Visible: true Script on mouseUp pop card into it — nothing happens to display pop card — now pop Directory card end mouseUp f ir, : ^ ; t; ii; button "Home" . i to £ Properties Location: 282.43 . ii.-- Rect; 266.30.298.57 AutoHllite: true ShowName: false HUite: false ' Style: transparent . ' l :-/, ; Icon: 20689 5: ; . r, Visible: true Script on mouseUp go home end mouseUp field "Name" Properties Location: 368.63 Rect; 250,53.486.74 LockText: false ShowLtnes: true WideMargins: false Style: transparent Text AUgn: center ^' ■ > Text Font: New York Text Height: 18 Text Size: 14 Text Style: bold Visible: true A Corporate Directory 615 field "Office" ~ the field containing the office number Properties Location: 203,307 Reel: 184,297.223.317 LockText: false ~ ^- -t- ShowLines: false WideMarglns: false , - , Slyle: transparent - ; Text Align: center Text Font: Chicago : Text Height: 16 Text Size: 12 Text Style: shadow, condense Visible: true Further Ideas There are many ways to streamline this stack. First, in locating the detail floorplan for a particular office, you could do away with the Office field and assign office numbers as card names. The hazard with this, however, is that a card name is easier to work with when It Is letters (or starts with letters) Instead of all numbers. When It's all numbers, the Go Card X command will go to a card number instead of to a card whose name is that number. But If the card name Is preceded with a word, like "cubicle," the script can stUl use the location global variable to help track that card. Before doing the Go command, precede item 2 of the location variable with the word "cubicle." Then go to that card name. Going to a card name Is inherently faster than finding a text string. To reduce the floorplan card count substantially, you could design the card so that each office has Its own opaque background button, sized to match the boundaries of each office. Each button would have a name linked to its office number. When the Zoom In button activates the floorplan card, that card's script sets the hlllte property of the desired office's button to true, turning It black. Perform a five-time repeat loop that sets the hiHte property to true and false alternately, making the office location flash on the screen several times. One more point. If you were to break out this environment into multiple stacks, two stacks should be sufficient, one with the actual directory, one with all the maps. Be sure that any Go commands pointing to cards In the other stack have the stack name as a parameter to the command. CHAPTER 40 A Telephone Logbook Many executtves and self-employed professionals need to record their outgoing telephone calls- the date and time, the person called, the phone number called, the content of the call, and to what account or project the time and phone call charges should be billed. What we'll show you here is the beginning of what could become an elaborate system. It ties directly into the Address stack supplied with HyperCard. Overview ^ ^ ; ' , Whenever you are in the Address stack (Figure 40-lJ and dial a call, a modified dial button script not only dials the number as it always did but also goes to a different stack of telephone logbook pages (Figure 40- 2) and generates a new card. When a new card is made, four items in the card are automatically filled in for you: the current date, the time, the name of the person appearing In the Address stack card you just dialed, and the phone number Just dialed. You may also generate a new card while in the Telephone Log stack by choosing New Card from the Edit menu. When you do this, the date and time are placed into the card. Because the card doesn't know whom you're calling, you'll have to type in the name and phone number. At any time while you are in the Log stack, you may check the person's Address stack card by clicking on the cards button in the upper right. That button's script goes to the Address stack and performs a search 617 618 Applying HyperCard and HyperTalk ^ % File Edit Go Tools Objects 555-&741 O % 2/23/37 <3 '1 ,■ L- -■ Figure 40-1. ^ 4t File Edit Go Tools Objects Figure 40=2. ■ * • • A Telephone Logbook 619 on the name in the Log card. If no match is found, you are given the choice to make a new Address stack card for this person or not. If you choose yes, a new Address card is made, placing the person's name in the Name spot and the phone number into the Phone Number field on the Address card. When you are finished with a call, you may click anywhere on a transparent button that Ues atop the field labeled Call Finished at. This action places the current time into the adjacent field. If there Is already an ending time in that field, a cUck of that button won*t accidentally overwrite the time. In practice, a professional person would perform a Message Box Find command on a project or client name when it comes time for bilUng. Also, if you are looking at a telephone bill and don't recognize a number, search for that number to find the outgoing phone call that generated the caU. Scripts and Properties We start with the dial button script In the Address stack, as revised for use with the Log stack. No other changes were made to the button or the rest of the Address stack. From there we move onto the scripts and properties of the Log stack. Refer to Figure 40-2 to get your bearings when we describe fields and buttons, ^ ^^v,> i o^ifj t'Uio-: stack "Address" hij.r,^ button "Dial" - - ' - • •;:!n-r^; ■ Script •: ■■ - ' • on mouseup if first char of selection Is In "(0123456789" then get selection else If first char of msg Is in "(0123456789" then get msg else get first line of field "Phone Number" if It Is not empty then put it into phoneNumber ■ • • ' ^ ' : ' put first line of field-i "Name and Address" into phoneName phone phoneNumber,phoneName end If . - , . end mouseUp 620 Applying HyperCard and HyperTalk on phone phoneNumber.phoneName .. ■ / visual effect zoom open ■ go to "Phone" dial phoneNumber set lockScreen to true ■ ■ ■; go to last card of Telephone Log" ' doMenu "New Card" put phoneName into field "Person" . i; i ■ put phoneNumber into field "Number" set lockScreen to false ■ - ?' end phone -i.; , ,^ CoMMEirr: This script is divided into two handlers for ease of readability and maintainability. Each handler performs a distinctly different task, The mouseUp handler determines whether the number is in a selection (as selected with the Text tool), the Message Box (as picked up by the Browse tool) , or just the first line of the Phone Number field. The handler is selective about using the selection or Message Box text. It only takes on the text if it starts with a number or a left parenthesis. If the text starts with anything else, it cannot possibly be a telephone number, Only when there is a number in It does the handler place the number and name into their respective variables (phoneNumber and phoneName). These variables are then passed as parameters to the ; phone handler, which performs the dialing action and then some. We could also have used global variables for the number and name, but since this information isn't needed beyond the phone handler, it's a bit "cleaner" to pass them as parameters. The phone handler accepts the parameters, assigning them to the same names as they had in the mouseUp handler (this is not necessaiy but sure makes it easier to keep track of the contents). Then we go to the Phone stack, dial the number (using the special settings in that stack), and lock the screen for the next bit of manipulation. In one command, we go to the last card of the Telephone Log stack to keep the new card in chronological order. When the new card is created, the Telephone Log stack's own newCard handler performs some things (you'll see in a moment) . Then the name and number are posted to the new log page. Setting lockScreen to false is optional, because it automatically reverts to false at idle time. stack "Telephone Log" bkgnd "Log Sheet" Script on newCard — happens after doMenu "New Card" In — phone handler of Address stack A Telephone Logbook 621 put t±ie long date into field "Date" put the time into field "Start" end newCard on openStack hide msg end openStack button "Prev" Properties Location; 241,302 Rect: 228,290,255,315 AutoHilite; false ShowName: false Hilite: false Style: transparent Icon: 1014 Visible: true Script on mouseUp visual effect scroll left go to prev card end mouseUp button "Neact" ^j^t Properties , ; . . , , Location; 270.302 •. ; '. Rect: 257,290,284,315 ; : AutoHilite; false : ShowName: false Hilite; false Style: transparent Icon: 1013 / < Visible; true i ; ; . ■ > . . > ' - Script ...^'-v.. ^- f on mouseUp ■ ■ visual effect scroll right ■■ go to next card ■ ■ ' • ■ end mouseUp ; ' button "To Home" Properties Location; 81,73 Rect: 68,62,95,84 AutoHilite; true 622 Applying HyperCard and HyperTalk ShowName: false ' - : • Hllite: false : Style: transparent " Icon: 20689 Visible: true Script on mouseUp visual effect iris close ' go home end mouseUp ? . ^ button "To Address" Properties , ■ Location: 423,71 Rect: 408.60,439,82 , . > AutoHllite: true ShowName: false Hilite: false Style: transparent Icon: 3430 . . , Visible: true : : v;'' Location: 406.132 Rect: 370.122.442,142 - ' (all other properties same as "Date") ' . 624 Applying HyperCard and Hypei^alk field "Person" Properties Location: 273,151 Rect: 162.141.384,161 (all other properties same as "Date"} field "Number" Properties _ Location: 305,169 ; - Rect: 227,159,384,179 (all other properties same as "Date") field "Comments" Properties > . Location; 294,222 Rect: 149.177,439,268 (aU other properties same as "Date") field "Charge To" Properties Location: 304,278 Rect: 169,268,439,288 (all other properties same as "Date") - " ' ■ ' ->\-A Further Ideas As you use this stack, you'll find many things you can add that will make its application more carefree. For Instance, you'll quickly discover that you leave many notes in the Comments field about getting a busy signal or no answer. You might want to add buttons that automaticalfy place those notes into the Comments field with the click of the mouse button. Another button you can add is one that redials the number in the current card. The handler for this wUl generate a new card and can)' over the name and number items into the new card's fields. You can always add buttons that link to other stacks you need while on the phone, like your calendar or appointment book. If you have other stacks that dial phone numbers, consider modifying those dial scripts to come to the Telephone Log stack and make a new card. Eventually, you can build a highly Integrated empire of telephone- related stacks. C H APTE R 41 A Time Sheet Many professional people must MAim-AiN records of time spent with cuents or on particular projects. These time sheets are then tabulated for billing purposes. When the professionals are part of a firm, an office manager or controller is usually responsible for distributing and collecting time sheets. By maintaining Ume sheets In a HyperCard stack, the sheets can be distributed electronically (either on disk or via a local area network). Moreover, the stack can be designed to encourage submis- sion of time sheets at the end of each billing period. When they're not turned in on time, the stack won't let the user enter any new sheets. Overview ' ' " . . The Time Sheets stack consists of two backgrounds. While the basic artwork for each background Is the same (the "Spiral Page" card id 62720 from the "Stack Ideas" stack), one background has no fields on It, while the other does. In the example of the cover card background in Figure 41-1, the artwork for the law firm name, field labels, and hourglass is all in the card graphics layer. The four fields are card fields. Information in this card would be filled out by the person responsible for distributing and tabulating the time sheets for the firm. The cover card shows for a couple of seconds whenever the stack opens, as a quick reminder of the period covered by the stack. Then the 625 626 Applying HyperCard and HypeiTalk '' i File Edit Go Tools Objects Figure 41-1 Stack moves to the last card in the stack, from which any new card Is generated {by the New Card menu command). If the current date is after the ending date of the period, the staci won't let the user create a new card. A dialog box advises what to do, Upon creation of a new card within a valid time period, the cunent date and time are placed in their respective fields (Figure 41-2). The hourly rate is retrieved from the cover card and placed In the appropriate field, The total billing amount is calculated after any of three actions: 1) pressing the "End" button; 2) changing the hourly rate on a card; or 3) adjusting the end time field. The End button places the current time into the End field and starts computation based on the elapsed time between the start and end times. The script that performs the calcula- tion has been designed in such a way that billing increments are by quarter-hour. Elapsed time display will always be displayed In quarter hour fractions of one hour. Sorting, as carried out by the handler in the Sort button scrlpl, arranges the cards in the stack by client name. Because cards are created in chronological order {always after the last card), then sordng by client will place each client's time sheets in chronological order fe easy tabulation into an Invoice. ; ' nti h A Time Sheet 627 Figure 41-2. Scripts and Properties Here are the objects and their scripts for the Time Sheet stack. stack "Time Sheet" Script on openStack go to last card end openStack bkgnd "Cover Card" card field "Attorney" Properties Location: 344,184 Rect: 218.174,470,194 LockText: false ShowUnes: true " WideMarglns: false ; Style: transparent Text Align: left 628 Applying HyperCard and HypefTaUc Text Font: Geneva Text Height: 18 Text Size: 14 " : Text Style: bold Visible: true ' "' ' ' • card field "Start Date" , - Properties ; -;;! ■ - >- ! ' . : ' Location: 227,217 Rect: 171,207,283,227 (all other properties the same as "Attorney") card field "End Date" Properties . Location: 367.217 Rect: 311,207,423,227 (all other properties the same as "Attorney") card field "Rate" Properties Location: 314,255 Rect: 258,245,370,265 (all other properties the same as "Attorney") bkgnd "Sheets" Script ■ ■ '■ ■: ' on doMenu item if item is not "New Card" then pass doMenu get card field "End Date" of card "Settings" convert it to seconds if it >= the seconds then pass doMenu else answer-i The period is over. Submit this file to Off. Mgr." end doMenu Macintosh clock, the doMenu "New Card" command is passed up HyperCard, so tliat it can make that new card. If it is now after theei date of the period, making a new card is out of the question. on newCard put the long date into field "Date" put the time into field "Start Time' A Time Sheet 629 put card field "Rate" of card "Settings" into field "Hourly" end newCard on computeBlll ' " ' > '■ it put field "Start Time" Into startTlme i t ► ' : > - ; . convert startnme to seconds . ■ ' ' • ■ put field "End Time" into endUme • - ■ i'-; convert endTime to seconds ' — ^ . put (endTime - startTime)/(60*15) into quarterHours put quarterHours - trunc(quarterHours) into fracQuarter put truncfquarterHours) into quarterCount if fracQuarter Is not zero then add 1 to quarterCount put quarterCount/4 into hours set numberFormat to "0.00" put quarterCount/4 Into field "Total Time" put hours * field "Hourly" into field 'Total Bill" . end computeBlll Cohmekt: The computeBlll handler is spaced Into three readable groups, each of which performs a distinctly different kind of operation in this handler. In the first group, the field information is retrieved and placed into variables for manipulation later in the handler. Notice that both times are converted into seconds. The numberFormat property is adjusted to allow for greater precision in calculating time in the following commands. Group two uses the start and ending time (In seconds) to calculate the number of quarter hours to be counted for billing purposes. Remember that the design calls for a fraction of a quarter hour to be billed as a complete quarter hour. The first line determines the raw number of quarter hours, virhich may have a fraction as part of it (for example, 5.34 quarter hours). The second line obtains that fractional amount (for example. 5.34 minus trunc(5.34) = 0,34). The whole number of quarter hours goes into the variable quarterCount in line 3 (for example, 5). Then line 4 checks whether the fractional quarter is zero. If It is, the quarter count is not adjusted upward (as in 5 hours and no fractions, which should be billed only as 5 hours). If the fraction is anything but zero, an additional quarter hour is tacked onto the total time to be billed. In the third group occurs the calculation of the Information that goes Into the fields. First comes the calculation of the number of hours (with the numberFormat adjusted to two places to the right of the decimal) and then the total bilUng amount. 630 Applying HyperCard and HypetTaSk button "End" Properties Location: 319,52 Rect: 290,41,348,63 AutoHilite: true ShowName: true r > Hllite: false Style: roundRect Icon: 0 . Visible: true , , Script , — . on mouseUp If field "End Time" Is empty then put the time into field "End Time" computeBill end If • - ... . ;» end mouseUp button "Sort" Properties ( ' ; . Location: 385.52 Rect: 359.41,412.63 "/ V AutoHilite: true ' ShowName: true ' ' Hilite: false ' " ' Style: roundRect Icon: 0 ' ■ • Visible: true - r; Script * ■ ' ; ; ■ ■ on mouseUp ' " sort by field "Client" ' ; end mouseUp . ' ^ ' button "Home" Properties i , , i' ■ ■> Location: 448,52 ^ ^ Rect: 422,41,475,63 AutoHilite: true ■ ShowName: true mute: false . ' ■ Style: roundRect . ,> ■• ; Icon: 0 ' ■ ■ - '^i^ ■ Visible: true ! i ' ' A Ttme Sheet 63 1 Script on mouseUp go home end mouseUp button "Prev" Properties Location: 247,308 Rect: 234,296.261,321 AutoHillte: false ShowName: false Hllite: false Style: transparent Icon: 1014 Visible: true Script on mouseUp go to prev card end mouseUp button "Next" Properties Location: 276,308 Rect: 263.296,290,321 AutoHillte: false ShowName: false Hmte: false Style: transparent Icon: 1013 Visible: true Script on mouseUp go to next card end mouseUp field "Date" Properties Location: 196,49 Rect: 103.39.289,59 LockText: false ShowLines: true WideMargins: false Style: transparent Text Align: left 632 Applying HyperCcmi and HyperTalk Text Font: Geneva Text Height: 16 Text Size: 12 Text Style: bold Visible: true Held "Start Time" Properties Location: 190,82 Rect: 141,72,239.92 (all other properties the same as "Date") field "End Time" Properties Location: 359,83 Rect: 307,73,411,93 [all other properties the same as "Date") Script on closeField computeBlll end closeField field "Client" Properties Location: 262,138 Rect: 112,128.412,148 (all other properties the same as "Date") field "Case Number" Properties Location: 283.172 Rect: 154,162,413,182 (all other properties the same as "Date") field "Purpose" Properties Location: 242,252 Rect: 73,212.412.293 (all other properties the same as "Date") field "Total Time" Properties Location: 181,111 Rect: 149,103,213,120 LockText: false ShowLines: false A Time Sheet 633 WldeMargins: false Style: rectangle Text Align: left Text Font: Geneva Text Height; 16 Text Size: 12 Text Style: plain Visible: true ; field "Hourly" Properties '. i . Location: 297, 111 Rect: 276,103,318,120 (all other properties the same as "Total Time") Script on closeFleld computeBill end closeFleld field "Total Bill" Properties Location: 379, 1 1 1 Rect: 347,103,412.120 (all other properties the same as 'Total Time") Further Ideas You can make the Sheets form behave even more like a relational database, if you like, by linking it to a stack containing client names and other data. By typing in the client's number, the Time Sheets stack could reach into the Client stack and fetch information like client name address, and quoted hourly rate. This stack also cries for many reporting possibilities using the Write to File command. This part of the stack would be used by the person who assembles the bills, but essentially a reporting script could write selected fields to a text file from all time sheets for a given client The file could be incorporated into a spreadsheet program or word proces- sor for generation of an invoice. CHAPTER 42 A New and Improved To Do List In this chapter, we'll enhance the To Do List stack first shown in chapter 17. If you make the changes as indicated in this chapter, you'll have not Just a rolling seven- day To Do stack, but a stack with a card for every day of the year. As a bonus, we throw in a script that makes cards for as many days as there are between a starting and an ending date you specily. . . . i.-.;, Overview " - ^ " To make the changes to the old stack, start with a new stack cloned from the original one. The new stack will ultimately look like the card showh in Figure 42-1. Use New Stack from the File menu to accomplish this, making sure you select the Copy Current Background button in the standard file dialog. Next erase the day buttons at the top. Following the properties and specifications listed below, add fields and buttons to the background, as shown in the button and field exposures in Figures 42- 2 and 42-3. Don't worry about the highlighting of the D, W, or M buttons. The scripts will take card of that. Anew feature added to this version is the ability to check off each item in a line. A narrow transparent text field is placed to the left of each items column. A transparent button is placed atop that field. When you click on the button at a particular line, a script places a check mark in the field directly below it. For one button to handle the entire column 635 636 Applying HyperCard and HyperTalk '' il File Edit Go Tools Objects Monday January 1 1, 19d8 nsRs.. V J.G.a t i, 0 n . re s e ry a t i.g ns... / PrgB are. Twee daje reaprt,..,. .Budget. mssy.n.9..co,ming,! <^ ^ Figure 42-1. ifc File Edit Go Tools Objects Monday January 11, 1966 . da R e..,v a c a t i.o n . re s e r v 8.!;.i o n s., , .Prepare. Tweedal.g.igE.grt, PMiiggt meeting. cotnlngl Figure 42-2. A New and Improved To Do List 637 Figure 42-3. requires a little math to measure the coordinates of a raouseclick, but it's not too difficult to understand. "Hie only tricity part of this stack is a hidden field called Interval. It is a background field (although it could also be a card field), whose content remembers which interval (Day, Week, or Month) you used the last time you worked with the stack. Upon opening the stack, the openStack handler retrieves the interval and places that information Into a global variable (also called interval), which the left and right buttons use to skip ahead or back in the stack at the desired interval. To create a hidden field, create it as you normally would. It may be of any size you like. Be sure you set its properties, especially its name. Then type hide field "Interval" into the Message Box. You won't be able to see it, but your scripts will be able to find it, put information into it, and retrieve from it as well. A second background of this stack environment is a stack maker (Figure 42-4). The openStack script is set up in such a way that if you have not made a supply of To Do cards with real dates in them, you come to the To Do Maker card. Here you specify the starting and ending dates of the sequence of cards you want generated. Upon pressing the OK button, a script takes over, making the cards you requested, plugging In the complete date as it goes. You will watch as each card is created and dated. 638 Applying HyperCard and. HyperTalk tt File Edit Go Tools Objects 1 3 "^1 To Do Card Maker specify starting date for the stack: 5/26/Q7 Specify ending date for the stack; i./26/aa '1,1 i ,™ , Cancel J i::^:!:i:E:t3i:t:i:i39:i::^3M:E figure 42-4. Once the stack is filled out with dated cards, the stack automatic goes to the current day's To Do card whenever you open the stadc. Pay special attention to the handlers in the To Do Form background script. Surprisingly, all script action for this stack (other than tk stack-making stuif. which you do only once in a blue moon) is contained in the background script. That means that even all the button activity on a card is handled by the background script. This is starting to get a bit advanced, but you should see how it Is done. The result is a remarkably compact application. Scripts and Properties Because the To Do Form background is actually the iirst back in the stack, its scripts and its objects wiU be listed first. The To Do , Maker background and its objects are listed later In this section. stock "My To Do 2.0" u,iuyii- Script Sit ; on openStack global interval A New and Improved To Do List 639 put field "Interval" of card 1 Into interval i u j : ; . ' ~ from the hidden field l i u: if the number of cards < 3 m ; u .ynf- '. :>v. >:.; then go to card "Setup" t ; : :u ' o J i - \ else isi->';':: ,f- ;ii ;•■ . , i . get word 2 to 4 of the long date ,}Vi< - / find it find today's card > end if . : endopenStack .^c ^ . - >. . /.i; .; l ; > on closeStack global interval put interval Into field "Interval" of card 1 — save our interval end closeStack ^ bk£nd "To Do Form" Script on mouseUp " ' — all mouse activity in the stack is performed — by this handler global interval ' ■ ' " ' • ' ' get short name of the target , , . , . . , * . . if it contains "checkoff' then ^ do it exit mouseup end if ' if "interval" is not in it then pass mouseUp set hUite of bkgnd button "D Interval" to it = "D Interval" set hilite of bkgnd button "W Interval" to it = "W Interval" set hilite of bkgnd button "M Interval" to it = "M Interval" put first word of it into Interval end mouseUp ' '~ Cohment: After reinitializing the global variable, this handler first sees if the object that received the last mouseUp message has the name Checkoff In it. As you'll see below, the buttons atop the check off fields are named Checkoff 1 and Checkoff 2. Notice that the next handler in this script is called Checkoff with a parameter looking for a column number. It turns out that the name of a Checkoff button can be used as the message that triggers the following handler. Since the short 640 Applying HyperCard and HyperTalk name of the target button contains the name of the object/handler, the It variable contains the appropriate command. By doing It, the script above Is saying the same as Checkoff 1 . The next command group in the above handler is looking for a target name that contains the word Interval. If the target doesn't contain that word, the mouseUp message Is passed up the hierarchy (where it will not find any other handlers). The three buttons that set the D, W, and M intervcil are called D Interval, W Interval, and M Interval, respectively, When you click the D Intervail button, for instance, this mouseUp handler processes It all the way to the set hllite commands. These commands adjust the hillte properties of the three buttons. When the button pressed is D Interval, the it = D Interval expression in the first set hihte line returns true. That turns on the highlighting for that button. The other two buttons are automatically set to false, because the short name {in It) Is not D Interval. Finally, the first word of the name (that Is, the letter) goes into the global variable, interval. This variable is used later, in the skip handler, on checkoff colNum put [item 2 of the cHckloc - 76) div 16 hito UneNum If line lineNum of bkgnd field ("OK" & colNum) Is empty then put "V" Into line HneNum of bkgnd field ("OK" & coINum) else put empty into line lineNum of-i bacl^ound field ("OK" & colNum) end checkoff Cohmekt: The first line of this handler calculates the line number of the underlying field that should get the check mark. It takes the second Item of the coordinates returned by the cllckloc function, subtracts 76 from it, and divides It by 16. The 76 represents the number of pixels from the top of the screen that line zero (that is, the line above the first line of the field) would be. The 1 6 is the line height of the text fleld. Each line is 16 pixels tall. When you click at the location atop the first line of the underlying field, a 1 is put into the lineNum variable. If it's empt)', the handler places the check mark (the character you get by pressing Optlon-v) into the corresponding line number of the "OK" field in the current column. If the line is not empty (meaning a check mark Is already there), the mark is removed, on skip direction , . global interval '' if interval is "D" or Interval Is ' W" then get number of this card if Interval Is "D" ' ' " ■ then add direction to it A New and Improved To Do Ust 641 else add direction * 7 to it , ^ go card it else . ; " ,, , get line 2 of field "Date" , v. • • •; o ,■ convert It to dateltems . put (item 2 of it + direction) mod 13 into item 2 of It if item 2 of it = 0 then put (13 + direction) mod 13 into Item 2 of it add direction to item 1 of It - end If i L jryi convert it to long date - .-^ ; ; ' :^ Uji, find (word 2 to 4 of it) , ^ , end If 'm-.i^-.r no^^^^ end skip ^ ' v H Coboient: This handler performs the skipping back and ahead through the cards, depending on which interval you have selected. The direction parameter, passed by the left and right arrow buttons, is either a -1 (back) or 1 (forward). When the interval variable Is D, the direction is added to the number of the current card, and the handler issues a Go command to that card number; when Interval is W, the direction times 7 (days in a week) Is added to the current card number, and the Go command sends you to the previous or next week, depending on the direction. Because the number of days in a month varies, you cannot simply add or subtract 30 days to the card and go there. You must invoke help from the date arithmetic facilities of HyperTalk. Starting with the date In the current card (it can work with the date parts in line 2 of the Date field), all necessary conversions are made, including accounting for the changeovers between years (when item 2 of dateltems is zero). Convert- ing the new date back to the long date format, the handler then applies the Find command to locate the card matching words 2 to 4 of the long date. button "D IntervaT ' c • ni^ Properties ; ' i,^ ;n..bs->!jj Location: 307,61 . ^ . H,. :■ ; , -i>- Recti 298,52,317.71 ' AutoHilite: false ■ i?.;.; ^or^S ShowName: false -cL-.i s w*; Hillte: false .. ^^^.iw! Style: transparent 'ri-f" .r ; .;^ Icon: 0 f< -i f ; ' Visible: true 642 Applying HyperCard and HyperTalk button "W Interval " -iv Properties ' ' ■ ^ Location: 329,61 Rect: 318,52,341,71 (all other properties the same as "D Interval") button "M Interval" ., ; \o Properties , - ,; , v Location: 352,61 v Rect: 342.52.362,71 (all other properties the same as "D Interval") button "To Calendar" Properties Location: 465,61 ' - Rect: 450,48,481,74 ' ' ' ■ AutoHilite: false ShowName: false Hillte: false , ' / ' ^' Style: transparent " ■ Icon: 15972 - Visible: true . -s^r -^i.-" ^'< »^ *- ' = ^ Script on mouseUp — from the original button in "Stack Ideas" ' " ' get "Jan 1. 1987" convert it to seconds ! , put 1 + (the seconds - it) dlv (60*60*24) into dayOfSfear ; ' *" put 1 + (dayOfiTear + 2) dlv 7 into whichWeek ' visual effect zoom open go to card (whichWeek + 2) of "Datebook" ' '' ■ ■ ' ' end mouseup button "To Name /Address" Properties i^v- Location: 433,61 Rect: 418,48,449,74 f - . AutoHilite: false ShowName: false HUite: false Style: transparent Icon: 3430 -in - visible: true A New and Improved To Do List 643 Script T i f.;i:,.i -^jfioq./io ■ ;/,» !,,. on mouseup "^-.i^ .jUH .a.t. get the selection . , . _ „ ,-, If it Is empty then get Msg ^ ^. _ ,^ ^~ ' ' go to stack "Address" , And it , . end mouseUp ' , ' ' button "DlaT* r J j; Properties . ; : -nj;; ■ Location: 400,61 t:' ;- \ Rect: 385.48,416,74 rtj AutoHllite: false : _ ShowName: false , - . , . ^ Hillte: false ' Style: transparent - (d. : ^ • Icon: 10610 Visible: true ^^'^-^^'^ Script on mouseUp _ visual effect zoom open ■ - get selection ] if it is empty then get msg ' go to "Phone" dial it ■ ■ go to 'Telephone Log" end mouseUp button "Checkoff 1" - no script needed ; . ..,; „ , r.o Properties , Location: 29.182 . j-j^-xj /tn Rect; 21,93,38,272 , . AutoHllite: false ^ r n^iju,: ShowName; false • >^ ^v- : - - Hillte; false -^o: Style: transparent ' ' ■ - -i Icon: 0 * ' • ■ ■ '••H Visible: true '"^^^ ' ^1 M button "Checker 2" ^ a : K properties ; 'r;q;>-MV Location: 266,182 Rect: 257,92.275.272 < - ia, 'i / 1 644 Applying HyperCard and HyperTalk (all other properties same as "Checkoff 1") button "Skip Back" ' Properties ^ Location: 375,77 " " '. Rect: 364,66.386,88 AutoHillte: true ShowName: false Hilite: false Style: transparent Icon: 1013 ,., r W: Visible: true , ' ; ^ - Script on mouseup : ; J skip -1 end mouseup • button 'Skip Ahead" Properties Location: 284,77 Rect: 274,66,295,88 AutoHilite: true "' ' ShowName; false Hilite: false , ■ ,0 Style: transparent Icon: 1014 , _ ^ . , Visible: true y -^. ^yi^^- - ^ Script . on mouseUp '1 .r>v skip 1 .• ■ end mouseUp V ^ : .. button "To Today's Card" -- located atop 'To Do" at upper left of card Properties Lxjcation: 65,69 " .. Rect: 31,53,99,85 AutoHilite: false ShowName; false Hilite: false tOi^i:- Style: transparent Icon: 0 i .